Skip to main content

Binary Tree Postorder Traversal

LeetCode 145 | Difficulty: Easy​

Easy

Problem Description​

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

Example 1:

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

Output: [3,2,1]

Explanation:

Example 2:

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

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

Explanation:

Example 3:

Input: root = []

Output: []

Example 4:

Input: root = [1]

Output: [1]

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?

Topics: Stack, Tree, Depth-First Search, Binary Tree


Approach​

Tree DFS​

Traverse the tree recursively (or with a stack). At each node, decide: what information do I need from the left/right subtrees? Process: go left β†’ go right β†’ combine results. Consider preorder, inorder, or postorder traversal based on when you need to process the node.

When to use

Path problems, subtree properties, tree structure manipulation.

Stack​

Use a stack (LIFO) to track elements that need future processing. Process elements when a "trigger" condition is met (e.g., finding a smaller/larger element). Monotonic stack maintains elements in sorted order for next greater/smaller element problems.

When to use

Matching brackets, next greater element, evaluating expressions, backtracking history.


Solutions​

Solution 1: C# (Best: 284 ms)​

MetricValue
Runtime284 ms
MemoryN/A
Date2018-05-03
Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public IList<int> PostorderTraversal(TreeNode root) {
Stack<TreeNode> s1 = new Stack<TreeNode>();
Stack<TreeNode> s2 = new Stack<TreeNode>();
List<int> postOrder = new List<int>();
if(root==null) return postOrder;
s1.Push(root);
while (s1.Count != 0)
{
var popped = s1.Pop();
s2.Push(popped);
if (popped.left != null)
{
s1.Push(popped.left);
}
if (popped.right != null)
{
s1.Push(popped.right);
}
}
while(s2.Count!=0)
{
postOrder.Add(s2.Pop().val);
}

return postOrder;
}
}

Complexity Analysis​

ApproachTimeSpace
Tree Traversal$O(n)$$O(h)$
Stack$O(n)$$O(n)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.
  • Consider: "What information do I need from each subtree?" β€” this defines your recursive return value.
  • Think about what triggers a pop: is it finding a match, or finding a smaller/larger element?