Binary Tree Postorder Traversal - Problem
Given the root of a binary tree, return the postorder traversal of its nodes' values.
In postorder traversal, we visit nodes in this specific order:
- Left subtree first
- Right subtree second
- Current node last
This traversal pattern is particularly useful for operations like deleting nodes, calculating directory sizes, or evaluating expression trees where you need to process children before their parent.
Example: For a tree with root 1, left child 2, and right child 3, the postorder traversal would be [2, 3, 1] - we visit the left child (2), then right child (3), and finally the root (1).
Input & Output
example_1.py โ Basic Tree
$
Input:
root = [1,null,2,3]
โบ
Output:
[3,2,1]
๐ก Note:
The tree has root 1 with right child 2, and 2 has left child 3. Postorder visits: left subtree of 2 (which is 3), then right subtree of 2 (empty), then 2 itself, finally root 1.
example_2.py โ Empty Tree
$
Input:
root = []
โบ
Output:
[]
๐ก Note:
An empty tree has no nodes to traverse, so the result is an empty list.
example_3.py โ Single Node
$
Input:
root = [1]
โบ
Output:
[1]
๐ก Note:
A tree with only one node. Since there are no children to visit first, we simply return the root node's value.
Visualization
Tap to expand
Understanding the Visualization
1
Start from Bottom
Begin with the lowest level rooms (leaf nodes) since they have no dependencies
2
Work Your Way Up
Clean each floor only after all floors below it are completely clean
3
Finish at the Top
The executive office (root) is cleaned last, after all other floors are done
Key Takeaway
๐ฏ Key Insight: Postorder traversal processes children before parents, like cleaning dependencies first. Use a stack to track visiting order and ensure proper sequence!
Time & Space Complexity
Time Complexity
O(n)
Visit each node exactly once
โ Linear Growth
Space Complexity
O(h + n)
Stack space O(h) for tree height plus O(n) for visited set
โก Linearithmic Space
Constraints
-
The number of the nodes in the tree is in the range
[0, 100] -
-100 <= Node.val <= 100 - Follow up: Recursive solution is trivial, could you do it iteratively?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code