Binary Tree Postorder Traversal (Iterative)
Binary Tree Postorder Traversal (Iterative) is a easy trees & bst problem solved with the recursion pattern.
The best approach, one stack with a last-visited pointer, runs in O(n) time and O(h) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from two stacks (reverse trick) up.
Problem
Return the postorder traversal of a binary tree iteratively. This is the trickiest of the three iterative traversals, because a node must wait until both subtrees are finished.
Examples
Example 1
- Input
root = [5, 3, 8, 1, 4]- Output
[1, 4, 3, 8, 5]
Example 2
- Input
root = []- Output
[]
Constraints
- The tree has
0to100nodes. - Solve it without recursion.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Two stacks (reverse trick) | O(n) | O(n) |
| One stack with a last-visited pointer | O(n) | O(h) |
1Two stacks (reverse trick)
O(n)O(n)Traverse node, right, left with one stack, pushing each popped node onto a second stack. Popping the second stack gives left, right, node.
- s1.push(root); pop into s2; push left then right onto s1.
- Pop everything from s2.
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> out = new ArrayList<>();
if (root == null) return out;
Deque<TreeNode> s1 = new ArrayDeque<>(), s2 = new ArrayDeque<>();
s1.push(root);
while (!s1.isEmpty()) {
TreeNode n = s1.pop();
s2.push(n);
if (n.left != null) s1.push(n.left);
if (n.right != null) s1.push(n.right);
}
while (!s2.isEmpty()) out.add(s2.pop().val);
return out;
}
}class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
out: List[int] = []
if root is None:
return out
s1, s2 = [root], []
while s1:
n = s1.pop()
s2.append(n)
if n.left is not None:
s1.append(n.left)
if n.right is not None:
s1.append(n.right)
while s2:
out.append(s2.pop().val)
return outclass Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> out;
if (root == nullptr) return out;
stack<TreeNode*> s1, s2;
s1.push(root);
while (!s1.empty()) {
TreeNode* n = s1.top(); s1.pop();
s2.push(n);
if (n->left != nullptr) s1.push(n->left);
if (n->right != nullptr) s1.push(n->right);
}
while (!s2.empty()) { out.push_back(s2.top()->val); s2.pop(); }
return out;
}
};function postorderTraversal(root) {
const out = [];
if (root === null) return out;
const s1 = [root], s2 = [];
while (s1.length > 0) {
const n = s1.pop();
s2.push(n);
if (n.left !== null) s1.push(n.left);
if (n.right !== null) s1.push(n.right);
}
while (s2.length > 0) out.push(s2.pop().val);
return out;
}2One stack with a last-visited pointer
O(n)O(h)Walk down the left spine. Peek the top: if it has an unvisited right child, go right. Otherwise visit it, pop it and remember it as last, so its parent knows the right subtree is done.
- While cur != null or the stack is not empty: push the left spine.
- top = peek(). If top.right != null and top.right != last: cur = top.right.
- Else visit top, last = pop().
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> out = new ArrayList<>();
Deque<TreeNode> st = new ArrayDeque<>();
TreeNode cur = root, last = null;
while (cur != null || !st.isEmpty()) {
while (cur != null) { st.push(cur); cur = cur.left; }
TreeNode top = st.peek();
if (top.right != null && top.right != last) {
cur = top.right;
} else {
out.add(top.val);
last = st.pop();
}
}
return out;
}
}class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
out: List[int] = []
st: List[TreeNode] = []
cur, last = root, None
while cur is not None or st:
while cur is not None:
st.append(cur)
cur = cur.left
top = st[-1]
if top.right is not None and top.right is not last:
cur = top.right
else:
out.append(top.val)
last = st.pop()
return outclass Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> out;
stack<TreeNode*> st;
TreeNode* cur = root;
TreeNode* last = nullptr;
while (cur != nullptr || !st.empty()) {
while (cur != nullptr) { st.push(cur); cur = cur->left; }
TreeNode* top = st.top();
if (top->right != nullptr && top->right != last) {
cur = top->right;
} else {
out.push_back(top->val);
last = st.top(); st.pop();
}
}
return out;
}
};function postorderTraversal(root) {
const out = [];
const st = [];
let cur = root, last = null;
while (cur !== null || st.length > 0) {
while (cur !== null) { st.push(cur); cur = cur.left; }
const top = st[st.length - 1];
if (top.right !== null && top.right !== last) {
cur = top.right;
} else {
out.push(top.val);
last = st.pop();
}
}
return out;
}Edge cases to test
- A node with only a right child
Hints
Hint 1
With one stack: go left as far as possible; a node is visited only when its right child is null or was just visited.
FAQ
What is the best time complexity for Binary Tree Postorder Traversal (Iterative)?
One stack with a last-visited pointer runs in O(n) time and O(h) extra space.
Which pattern does Binary Tree Postorder Traversal (Iterative) use?
It is a trees & bst problem that uses the recursion pattern. Other problems with the same pattern: Binary Tree Inorder Traversal (Recursive), Binary Tree Preorder Traversal (Recursive), Binary Tree Postorder Traversal (Recursive).
Is there a brute force solution for Binary Tree Postorder Traversal (Iterative)?
Yes. Two stacks (reverse trick) takes O(n) time and O(n) space. Traverse node, right, left with one stack, pushing each popped node onto a second stack.
Which edge cases should I test for Binary Tree Postorder Traversal (Iterative)?
A node with only a right child.