Binary Tree · Traversal

Postorder Traversal

Visit nodes in Left → Right → Root order. The root is always the last node visited.

RecursionDFSInterview Essential

Key concepts at a glance — for those who already know the basics.

Problem Statement

Binary Tree Postorder Traversal

Given the root of a binary tree, return the postorder traversal of its node values.
Example 1

Input: root = [1, null, 2, 3]

Output: [3, 2, 1]

Tree: 1 → right child 2, left child of 2 is 3.

Example 2

Input: root = [1, 2, 3, 4, 5, 6, 7]

Output: [4, 5, 2, 6, 7, 3, 1]

Perfect binary tree — left subtree, right subtree, root.

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • Each node's value is in the range [-100, 100].
01

The Rule

Left → Right → Root

Both subtrees are fully processed before you ever visit the current node. The root is always last.

02

How to Think

1

Recurse all the way into the left subtree

Do not visit the current node yet — go left first.

2

Then recurse into the right subtree

Still don't visit the current node — right subtree must finish too.

3

Only then visit (record) the current node

A parent is always visited after both its children.

03

Code

solution.py
def postorder(node, result):
if node is None: return # base case
postorder(node.left, result) # 1. left
postorder(node.right, result)# 2. right
result.append(node.val) # 3. root
04

Complexity

Time

O(n)

Every node visited once.

Space

O(h)

Stack depth = tree height.

05

Interview Uses

Delete a tree

Delete children before the parent (safe cleanup).

Evaluate expression trees

Evaluate operands before the operator.

Height / depth of tree

Compute children heights before parent.

Path sum problems

Propagate info upward from leaves to root.

Ready to see it in action?

Step through the visualizer to watch the algorithm state update live.

Open Visualizer