Problem
Given theroot of a binary tree, return the postorder traversal of its nodes’ values.
Examples
Constraints
- The number of nodes in the tree is in the range [0, 100].
- -100 <= Node.val <= 100
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 145 with 15 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 145 # by problem number
lcpy gen -s binary_tree_postorder_traversal # by problem name
root of a binary tree, return the postorder traversal of its nodes’ values.
Input: root = [1,null,2,3]
Output: [3,2,1]
Input: root = [1,2,3,4,5,null,8,null,null,6,7,9]
Output: [4,6,7,5,2,9,8,3,1]
Input: root = []
Output: []
Input: root = [1]
Output: [1]
from leetcode_py import TreeNode
class Solution:
# Time: O(n)
# Space: O(h) where h is the height of the tree
def postorder_traversal(self, root: TreeNode[int] | None) -> list[int]:
if not root:
return []
result: list[int] = []
stack: list[TreeNode[int]] = [root]
while stack:
node = stack.pop()
result.append(node.val)
# Push left first, then right (so right is processed first)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
# Reverse to get postorder (left, right, root)
return result[::-1]
| Time | Space |
|---|---|
| O(n) | O(h) where h is the height of the tree |