🌳 Postorder Traversal in Binary Tree (Recursive & Iterative) #145
Given the root of a Binary Tree, return the postorder traversal of its nodes.
👉 Postorder Traversal Order:
Left → Right → Root
Postorder traversal is the most “bottom-up” traversal.
It is heavily used in:
- Deleting a tree
- Tree DP problems
- Height / Diameter / Balance checks
- Expression tree evaluation
If preorder says “me first” and inorder says “me in between” then postorder says:
“Kids first… I’ll go last.” 😌
Binary Tree:
1
/ \
2 3
/ \
4 5
4 5 2 3 1
class Solution {
public:
void postorderTraversal(TreeNode* root, vector<int>& result) {
if (!root) return;
postorderTraversal(root->left, result);
postorderTraversal(root->right, result);
result.push_back(root->val);
}
};If root is NULL:
return
Postorder(left)
Postorder(right)
Visit root
- Time: O(N)
- Space: O(H) recursion stack (H = height of tree)
- When tree depth is small
- When clarity matters more than stack limits
- When interviewer doesn’t restrict recursion
This is the most common iterative postorder solution.
vector<int> postorderTraversal(Node* root) {
vector<int> postorder;
if (!root) return postorder;
stack<Node*> st1, st2;
st1.push(root);
while (!st1.empty()) {
Node* node = st1.top();
st1.pop();
st2.push(node);
if (node->left) st1.push(node->left);
if (node->right) st1.push(node->right);
}
while (!st2.empty()) {
postorder.push_back(st2.top()->val);
st2.pop();
}
return postorder;
}Postorder =
Left → Right → Root
But iterative traversal naturally gives:
Root → Left → Right
So the trick is:
- Generate Root → Right → Left
- Reverse it → Left → Right → Root
That’s exactly what two stacks do 🎯
- Push root into
st1 - Pop from
st1, push intost2 - Push left & right children into
st1 - Once done, pop from
st2→ postorder
- Time: O(N)
- Space: O(N) (two stacks)
✔ No recursion ✔ No stack overflow risk
| Tree Type | Output |
|---|---|
| Empty tree | [] |
| Single node | [1] |
| Left skewed | bottom → root |
| Right skewed | bottom → root |
| Balanced tree | children before parent |
| Aspect | Recursive | Iterative (2 stacks) |
|---|---|---|
| Simplicity | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
| Space | O(H) | O(N) |
| Stack overflow risk | Yes | No |
| Interview usage | Very common | Very common |
❌ Forgetting root null check
❌ Pushing children in wrong order
❌ Mixing preorder logic
❌ Forgetting why reversal is needed
- Postorder using single stack (harder)
- Morris Postorder Traversal (O(1) space)
- Tree deletion
- Expression tree evaluation
- Diameter / height / balanced tree checks
Because root comes last, not first or middle.
👉 Two-stack approach It’s the safest and most explainable.
- Very deep trees
- Memory-restricted environments
Almost never ❌ Good to know, not required.
No ❌ Only inorder traversal sorts BST values.
Postorder = Left → Right → Root
Recursive = easiest
Iterative = reverse (Root → Right → Left)
Two stacks = safest