Binary Tree Postorder Traversal

easy

Given the root of a binary tree, return the postorder traversal of its nodes' values — visit the left subtree, then the right subtree, then the node last.

The tree is given in level-order (breadth-first), using null for missing children.

Hints

Postorder means the left subtree, then the right subtree, then the node.
Recursively that's three lines with the node recorded last.
Iteratively, run a node-right-left stack walk and reverse the result.

Common doubts

Those values depend on the children's results, and postorder guarantees both subtrees are fully processed before the parent.
The reverse of the sequence (node, right, left) is (left, right, node), which is exactly the postorder definition.
O(height) recursively; the reversed-walk version uses O(n) for the output list it reverses.

Interview follow-ups

Track a lastVisited pointer: only pop and record a node once its right child has been visited, otherwise descend right first.
You must free both children before the parent, so you delete in left-right-node order — postorder.

Fun facts

  • Postorder is how a compiler evaluates an expression tree: operands (children) before the operator (parent).
  • Reverse-Polish notation is exactly the postorder traversal of an expression tree.

Asked at

AmazonMicrosoftFacebook
Frequently Sometimes Occasionally
Example 1
Input: root = [1, null, 2, 3]
Output: [3, 2, 1]
Left subtree (empty), then the right subtree yielding 3 then 2, then the root 1 last.
Example 2
Input: root = []
Output: []
An empty tree has no nodes.
Constraints

- The number of nodes is in the range [0, 100] - -100 <= Node.val <= 100

Solve this problem →