LeetCode #145 Easy

Binary Tree Postorder Traversal

Binary Tree Postorder Traversal is LeetCode 145 (Easy). Given the root of a binary tree, return its node values in postorder: the left subtree, then the right subtree, then the node.

  • The tree can be empty; then the answer is [].
  • Follow-up: the recursive solution is trivial, so do it iteratively.

With at most 100 nodes any O(n) walk is fast; the hard part is that a node must wait for both of its subtrees.

Constraints
  • The number of the nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100
binary treedfsrecursion
Open on LeetCode ↗
02

Intuition

An iterative postorder traversal keeps waiting nodes on a stack, as inorder does. The difference is that a node on top of the stack can be in two situations:

  • Right subtree not visited yet: leave the node where it is and go into its right child first.
  • Right subtree finished, or missing: the node is ready; pop it and record it.

A pointer last, the node recorded most recently, tells the two apart. A subtree's root is always the last of its nodes to be recorded, so the right subtree is finished exactly when the right child is last.

How to spot this pattern

Postorder is the order for anything a node computes from its children's answers: a tree's height, subtree sums, checking whether a tree is balanced, deleting a tree, evaluating an expression tree. Maximum Depth of Binary Tree and Diameter of Binary Tree are postorder walks written as recursion.

03

Approach

Try it first

Before reading on: in [1,null,2,3] the answer is [3, 2, 1]. Node 1 is reached first but recorded last. When 1 is on top of your stack and its right child 2 still exists, how can you tell whether 2's subtree is still to do or already finished?

1

Walk left, pushing every node

From node, push it and move to node.left until node is empty. Each pushed node is waiting for both of its subtrees, and the left one comes first in postorder.

2

Check the top's right child

Look at the top of the stack without popping it. If it has a right child and that child is not last, the right subtree has not been visited: set node to the right child and go back to the first step. The parent stays on the stack, because it comes after that subtree.

3

Otherwise pop and record

With no right child, or a right child equal to last, both subtrees are finished. Pop the node, append its value and set last to it. When its parent reaches the top, this is how the parent sees that its right subtree is done.

4

Stop when both are empty

The loop runs while node or the stack is non-empty. When both are empty, every node has been pushed, popped and recorded, and the root, recorded last, closes the list.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
▶3 result, stack = [], []
▶4 node, last = root, None
▶5 while node or stack:
▶6 while node:
▶7 stack.append(node)
▶8 node = node.left
▶9 top = stack[-1]
▶10 if top.right and top.right is not last:
▶11 node = top.right
▶12 else:
▶13 result.append(top.val)
▶14 last = stack.pop()
▶15 return result
in answeron stack123stack1topansweremptypush 1, no left child
push1waits for both subtrees
stack[1]top on the right
Start at the root. Push 1: it cannot be recorded until both of its subtrees are, so it waits on the stack. It has no left child, so the walk left stops here.
in answeron stack123stack1topansweremptytop 1: right child 2 not done → go right
top1stays on the stack
right2nothing recorded yet
stack[1]
Look at the top, 1, without popping it. Its left side is done, but its right child 2 is not the last node recorded, so that subtree has not been visited. 1 stays put and the walk moves into the right subtree.
in answeron stack123stack12topansweremptypush 2, then go left
push2waits for both subtrees
stack[1, 2]top on the right
Push 2. Like every node on the stack, it waits until both of its subtrees are recorded. Keep walking left, because the left subtree comes first in postorder.
in answeron stack123stack123topansweremptypush 3, no left child
push3waits for both subtrees
stack[1, 2, 3]top on the right
Push 3. Like every node on the stack, it waits until both of its subtrees are recorded. It has no left child, so the walk left stops here.
in answeron stack123stack12topanswer3lastno right child → record 3
record3both subtrees finished
last3marks this subtree as done
result[3]1 of 3
The top is 3 and 3 is a leaf, so both of its subtrees are finished. Pop it, record it and set last to it. The next check looks at 2.
in answeron stack123stack1topanswer32lastno right child → record 2
record2both subtrees finished
last2marks this subtree as done
result[3, 2]2 of 3
The top is 2 and 2 has no right child, so both of its subtrees are finished. Pop it, record it and set last to it. The next check looks at 1.
in answeron stack123stackemptyanswer321lastright child 2 done → record 1
record1both subtrees finished
last1marks this subtree as done
result[3, 2, 1]3 of 3
The top is 1 and its right child 2 is the last node recorded, so both of its subtrees are finished. Pop it, record it and set last to it. A subtree's root is always the last of its nodes to be recorded, which is how the check knew.
in answeron stack123stackemptyanswer321stack empty → return [3, 2, 1]
result[3, 2, 1]left, right, node
work3 pushes, 3 popsO(n)
Done. Nothing is left to walk and the stack is empty. Each node was pushed once and popped once, and it was recorded only after both of its subtrees, which is postorder.
05

Recursive postorder traversal

dfs(node) returns at once on an empty node; otherwise it visits the left subtree, then the right subtree, and only then appends node.val. The call stack remembers which node to return to.

▶1class Solution:
▶2 def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
▶3 result = []
▶4 
▶5 def dfs(node):
▶6 if not node:
▶7 return
▶8 dfs(node.left)
▶9 dfs(node.right)
▶10 result.append(node.val)
▶11 
▶12 dfs(root)
▶13 return result
06

Common pitfalls

Checking only that a right child exists

✗ Wrong
if top.right:
    node = top.right
✓ Right
if top.right and top.right is not last:
    node = top.right

After the right subtree is recorded, the parent is on top again and its right child is still there. Without the last check the walk goes into the same subtree again and never stops.

Popping the node before its right subtree

✗ Wrong
top = stack.pop()
result.append(top.val)
node = top.right
✓ Right
top = stack[-1]
if top.right and top.right is not last:
    node = top.right
else:
    result.append(top.val)
    last = stack.pop()

Recording a node as soon as its left side is done gives inorder, not postorder. For [1,2,3] the answer comes out [2, 1, 3] instead of [2, 3, 1].

07

Complexity

Time
O(n)
Space
O(h)
Each node is pushed and popped once. The stack holds one root-to-node path; at most n nodes for a chain.
08

Binary Tree Postorder Traversal FAQ

How does postorder traversal using two stacks work?

Run a preorder that visits node, right, left: pop a node from the first stack, push it onto the second, then push its left child and then its right child onto the first. When the first stack is empty, popping the second gives left, right, node, which is postorder. It is simpler to write but stores every node before any is output, so it uses O(n) space. With one list, append instead of pushing to the second stack and reverse it at the end.

Can it be done in O(1) extra space?

Yes, with Morris traversal. It threads the rightmost node of each left subtree back to its parent so it can climb up without a stack, and when it returns along a thread it outputs that left subtree's right edge in reverse. Time stays O(n) and the tree is restored, but the code is long and rarely asked for.