Binary Tree Postorder Traversal (LeetCode 145): Solution and Explanation

Easy
Stack
Tree
Depth First Search
Binary Tree

Given the root of a binary tree, return its values in postorder: the left subtree, then the right subtree, then the node itself. The tree has up to 100 nodes and may be empty. Recursion is trivial, so the real question is how to do it with explicit stacks.

Intuition

Postorder is the awkward one to do iteratively, because a node must wait until both of its subtrees are finished. When you first reach a node you cannot record it yet.

Reverse the target order and the problem gets easy. Left, right, root reversed is root, right, left, and that is just preorder with the children swapped. A stack produces it directly: pop a node, record it, push the left child and then the right child so the right one comes off first.

Instead of recording into a list, record onto a second stack. When the first stack runs dry, the second one holds root, right, left from bottom to top, so popping it yields left, right, root.

Approach: Two stacks (mirrored preorder, then reverse)

  1. If the root is null, return an empty list.
  2. Push the root onto s1.
  3. While s1 is not empty, pop a node and push it onto s2.
  4. Push its left child, then its right child, onto s1, skipping missing ones.
  5. When s1 is empty, pop every node off s2 and append its value to res.
  6. Return res.

Step-by-step example

root = [5,3,8,1,4,7,9]
  1. s1 = [5]. Move 5 to s2 and push 3, then 8. s1 = [3,8], s2 = [5].
  2. Move 8 to s2 and push 7, then 9. s1 = [3,7,9], s2 = [5,8].
  3. Move the leaves 9 and then 7 to s2. s1 = [3], s2 = [5,8,9,7].
  4. Move 3 to s2 and push 1, then 4. Move the leaves 4 and then 1. s2 = [5,8,9,7,3,4,1].
  5. s1 is empty. Pop s2 from the top: 1, 4, 3, 7, 9, 8, 5.
  6. Return [1,4,3,7,9,8,5].

Code: Python, Java, C++

1class Solution:
2    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
3        if not root:
4            return []
5        s1, s2 = [root], []
6        while s1:
7            node = s1.pop()
8            s2.append(node)
9            if node.left:
10                s1.append(node.left)
11            if node.right:
12                s1.append(node.right)
13        res = []
14        while s2:
15            res.append(s2.pop().val)
16        return res
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each node is pushed and popped once on s1 and once on s2.

Space

O(n)

s2 eventually holds every node, so the extra space is O(n) regardless of the tree's shape.

Other approaches

Recursion (time O(n), space O(h))

Recurse on the left child, recurse on the right child, then append the node's value. The call stack does all the bookkeeping.

One stack with a last-visited pointer (time O(n), space O(h))

Walk left pushing nodes. Peek at the top: if it has an unvisited right child, go right; otherwise pop and record it and remember it as last visited. Uses only O(h) space but is easier to get wrong.

Mirrored preorder into a list, then reverse (time O(n), space O(n))

The same idea as two stacks, but append to res and reverse it once at the end instead of using a second stack.

Common mistakes

  • Pushing the right child before the left onto s1. That produces root, left, right on s2, and reversing it gives right, left, root, not postorder.
  • Recording values when a node is first reached. In postorder a node comes after its subtrees, which is why the second stack is needed.
  • Forgetting the empty tree before pushing the root.
  • Assuming the one-stack version is simpler. Without the last-visited check it loops forever or records a node before its right subtree.

Frequently asked questions

Is the two-stack version really postorder, or just something that looks like it?

It is exact. s1 produces the root, right, left order one node at a time, and s2 stores those nodes in that order. Popping s2 reads them backwards, and the reverse of root, right, left is left, right, root.

Why use two stacks when one would do?

The two-stack version is the easiest to get right in an interview because each loop is simple. The one-stack version saves memory on balanced trees but needs careful handling of when to visit a node.

Where is postorder useful?

Whenever a node depends on results from its children: deleting a tree, computing subtree sizes or heights, or evaluating an expression tree.