DSA Factory
Free Trees lessonsTrees · Stage 1 · Traversals · Step 3

Postorder traversal

Visit both children before the root — the order to use whenever a node's answer needs its children's answers first. About 8 minutes.

Left, then right, then root

Postorder of a tree means: do postorder on the left subtree, then on the right subtree, and only then write down the node's own value. "Post" means after, so the parent is recorded after both of its children.

It is like a teacher who will not record the class result until every student has handed in their work.

Current value last: the node is written down after both of its subtrees.
Both children first: neither subtree can be skipped before the root is recorded.
In code
if not root:
    return []
out = postorder_traversal(root.left)
out += postorder_traversal(root.right)
out.append(root.val)
return out
Postorder on [5, 3, 8, 1, 4]: left, then right, then me
1sum 13458
result
[1]

Dive to the bottom-left first. 1 has no children, so it's done: visit it.

Move 1 of 5

Why "children before parent" is useful

Some questions can only be answered once you already know the answer for both children. For example, "what is the sum of this subtree?" needs the left and right sums before it can add its own value.

Postorder guarantees both children are fully processed before their parent, so this kind of bottom-up work always has what it needs by the time it reaches the parent.

Bottom-up: children finish before their parent combines results.
Deleting a tree: you must free both children before the node that points to them.
Quick check

For the tree with root 5, left child 3, and right child 8, what does postorder traversal return?

  1. A[3, 8, 5]
  2. B[5, 3, 8]
  3. C[3, 5, 8]
Show the answer

[3, 8, 5]. Left subtree (3), then right subtree (8), then the root (5) last.

Your problem

Postorder traversal

Given the root of a binary tree, return the values of its nodes visited in postorder: every node in its left subtree, then every node in its right subtree, then the current node. If the tree is empty, return an empty list.

Example
root = [5, 3, 8] → [3, 8, 5]

0 ≤ number of nodes ≤ 10,000 · -1,000,000 ≤ node.val ≤ 1,000,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve