Binary Tree Postorder Traversal - Problem

Given the root of a binary tree, return the postorder traversal of its nodes' values.

In postorder traversal, we visit nodes in this specific order:

  1. Left subtree first
  2. Right subtree second
  3. Current node last

This traversal pattern is particularly useful for operations like deleting nodes, calculating directory sizes, or evaluating expression trees where you need to process children before their parent.

Example: For a tree with root 1, left child 2, and right child 3, the postorder traversal would be [2, 3, 1] - we visit the left child (2), then right child (3), and finally the root (1).

Input & Output

example_1.py โ€” Basic Tree
$ Input: root = [1,null,2,3]
โ€บ Output: [3,2,1]
๐Ÿ’ก Note: The tree has root 1 with right child 2, and 2 has left child 3. Postorder visits: left subtree of 2 (which is 3), then right subtree of 2 (empty), then 2 itself, finally root 1.
example_2.py โ€” Empty Tree
$ Input: root = []
โ€บ Output: []
๐Ÿ’ก Note: An empty tree has no nodes to traverse, so the result is an empty list.
example_3.py โ€” Single Node
$ Input: root = [1]
โ€บ Output: [1]
๐Ÿ’ก Note: A tree with only one node. Since there are no children to visit first, we simply return the root node's value.

Visualization

Tap to expand
๐Ÿ—๏ธ Postorder Traversal: Building CleanupExecutive Office (1)Clean LAST โœ“Floor 2Clean 1st โœ“Floor 3Clean 2nd โœ“Cleanup Order231Result: [2, 3, 1]Left โ†’ Right โ†’ Root๐Ÿ’ก Key InsightDependencies must be resolvedbefore processing parent nodesStack helps track what needsto be processed next
Understanding the Visualization
1
Start from Bottom
Begin with the lowest level rooms (leaf nodes) since they have no dependencies
2
Work Your Way Up
Clean each floor only after all floors below it are completely clean
3
Finish at the Top
The executive office (root) is cleaned last, after all other floors are done
Key Takeaway
๐ŸŽฏ Key Insight: Postorder traversal processes children before parents, like cleaning dependencies first. Use a stack to track visiting order and ensure proper sequence!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Visit each node exactly once

n
2n
โœ“ Linear Growth
Space Complexity
O(h + n)

Stack space O(h) for tree height plus O(n) for visited set

n
2n
โšก Linearithmic Space

Constraints

  • The number of the nodes in the tree is in the range [0, 100]
  • -100 <= Node.val <= 100
  • Follow up: Recursive solution is trivial, could you do it iteratively?
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
125.0K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen