#145
Binary Tree Postorder Traversal
EasyStackTreeDepth-First SearchBinary TreeDepth-First Search (DFS)Stack-based traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses an iterative approach with a stack to simulate the postorder traversal without recursion. This avoids the overhead of recursive calls and allows us to manage the traversal more efficiently.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty stack and a result list.
- 2Step 2: Push the root node onto the stack.
- 3Step 3: While the stack is not empty, pop a node from the stack and add its value to the result list.
- 4Step 4: Push the left child first, then the right child onto the stack (if they exist).
- 5Step 5: Reverse the result list before returning it, as we collected values in root-right-left order.
solution.py12 lines
1def postorderTraversal(root):
2 if not root:
3 return []
4 stack, result = [root], []
5 while stack:
6 node = stack.pop()
7 result.append(node.val)
8 if node.left:
9 stack.append(node.left)
10 if node.right:
11 stack.append(node.right)
12 return result[::-1]ℹ
Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(n) due to the stack storing nodes in the worst case (for a completely unbalanced tree).
- 1Postorder traversal visits nodes in the order of left-right-root.
- 2Using a stack allows us to simulate recursion and control the order of node processing.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.