15% off all plans & roadmaps Use code

See plans

Binary Tree Postorder Traversal

Updated

TL;DR: You must return the values of a binary tree in postorder, which means left subtree, right subtree, then the node. Recurse into both children and record the node last, or use an explicit stack and reverse the output.

Problem

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]

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]

Example 3

Input: root = []
Output: []

Example 4

Input: root = [1]
Output: [1]

Constraints

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

Constraints that matter

  • The tree has at most 100 nodes, so recursion depth is at most 100. Recursion is safe here, but a 10^5-node chain would overflow the call stack.
  • n up to 100 does not rule out the O(n^2) concatenation, so you must argue with growth rate, not with timing on small inputs.
  • Node values range from -100 to 100, but the solution never uses values as keys or indexes. Do not build a counting array.
  • The root can be null. The empty input must return an empty list, so every approach needs a null base case.

View on LeetCode

Hints

Hint 1

This problem asks for a fixed visiting order.

Hint 2

Write the definition as code.

Solution

Intuition

This problem asks for a fixed visiting order. Every value must appear after all values in its left and right subtrees, and before nothing else in that subtree. A depth-first walk that records the node after both child calls return produces exactly that order.

Picture a pile of order slips where you take the top slip, write its name on a sheet, and place its children's slips on top. The pile is the explicit stack, the sheet is the out list, and reading the sheet bottom to top gives postorder.

To recognise it, look at what the answer depends on. The position of a node in the output depends on the subtrees below it, not on the nodes above it. So you process the children first and append the parent last. This is the Tree DFS pattern with postorder ordering.

A recursive call returns only after its whole subtree is done. A subtree's values therefore form one contiguous block in the output, and the subtree's root closes that block. Each node is recorded once, at the moment its subtree is finished.

Watch the pattern animation

Worked example

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: The level-order array builds the tree 1(2(4, 5(6, 7)), 3(null, 8(9, null))). Postorder visits the left subtree, then the right subtree, then the node. So 4 comes first, then 5's subtree (6, 7, 5), then 2. Node 3 comes after the subtree of 8 (9, 8), and the root 1 comes last.

Approach 1: Brute force: concatenate child lists

Write the definition as code. The postorder list of a node is the postorder list of its left child, then the postorder list of its right child, then the node's value. Each call returns a new list, and the parent joins the two child lists onto its own value.

This is correct, but joining lists copies data. A node at depth d is copied once by each of its d ancestors. On a chain of n nodes, the copying adds up to roughly n^2 / 2 element moves.

Steps

  1. If the node is null, return an empty list.
  2. Recursively get the postorder list of node.left.
  3. Recursively get the postorder list of node.right.
  4. Build a new list with the left values, then the right values, then node.val.
  5. Return the new list to the parent call.

Dry run

Trace the example tree. The leaves return one-element lists: 4 gives [4], 6 gives [6], 7 gives [7], and 9 gives [9]. Node 5 joins [6] and [7] and its value, giving [6, 7, 5]. Node 2 joins [4] and [6, 7, 5], then adds 2, giving [4, 6, 7, 5, 2].

Node 8 gives [9, 8], and node 3 gives [9, 8, 3] because its left child is null. The root joins [4, 6, 7, 5, 2] with [9, 8, 3] and adds 1. The result is [4, 6, 7, 5, 2, 9, 8, 3, 1].

Complexity

TimeO(n^2)
SpaceO(n^2) allocated in total

Let n be the number of nodes. Each node's value is copied once for every ancestor, because each ancestor builds a new list from its children's lists. On a chain of n nodes the depths are 0 through n - 1, so the copies sum to n(n - 1) / 2, which is O(n^2). Each copy allocates memory, so the total allocated space is also O(n^2).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if root is None:
            return []
        # Copy both child lists, then add this node's value
        return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val]

The Recursive Postorder Traversal infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Recursive Postorder Traversal

Part of Tree Traversal Patterns (DFS & BFS)

Approach 2: Recursion with one shared listRecursive Postorder Traversal

What is slow in the first approach is the copying. The output order is the order in which the recursion finishes each node, so you can build the answer in one list in that same order. Pass the same list down the recursion, and append a node's value after both recursive calls return.

This removes all copying. Each node is appended exactly once, and each call does constant work besides its two recursive calls.

Steps

  1. Create one empty list result outside the recursion.
  2. Write traverse(node). If node is null, return.
  3. Call traverse(node.left), then traverse(node.right).
  4. Append node.val to result.
  5. Call traverse(root) and return result.

Dry run

Trace the example tree. Going down the left side, the calls reach 4 first. Node 4 has no children, so 4 is appended. Back at 2, the walk goes right into 5, which goes into 6.

Node 6 is appended, then 7, then 5 after both children. Node 2 is appended when its right side is done. Back at the root, the walk goes into 3, which has no left child, then into 8.

Node 9 is appended, then 8, then 3, and finally the root 1. The list is [4, 6, 7, 5, 2, 9, 8, 3, 1].

Complexity

TimeO(n)
SpaceO(h) for the call stack

Let n be the number of nodes and h the height of the tree. Each node causes one call to traverse and one append, and each call does constant work apart from its children. That gives O(n) time. The call stack holds one frame per node on the current path, so it reaches h frames, which is O(n) on a skewed tree and O(log n) on a balanced one.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        result = []

        def traverse(node):
            if node is None:
                return
            traverse(node.left)
            traverse(node.right)
            result.append(node.val)

        traverse(root)
        return result

Approach 3: Iterative with explicit stack, then reverseOptimal

Recursion uses the call stack, which the follow-up asks you to replace. Reverse postorder is root, then right subtree, then left subtree. That order is easy to produce with a stack. Pop a node, record it, then push its left and right children.

Because the right child is pushed last, it is popped first, so the right side is recorded before the left side. Reverse the recorded list at the end. Root, right, left, read backwards, is left, right, root. The time is O(n), and the only extra memory is the stack.

Why it is correct. Each node is popped only after its parent, so the parent is written before all of its descendants. The right child is pushed after the left, so the right subtree is written before the left subtree. Reversing that root, right, left sequence turns every subtree into a contiguous block that ends at its root, which is postorder.

Steps

  1. If the root is null, return an empty list.
  2. Push the root onto a stack.
  3. Pop a node and append its value to out.
  4. Push its left child if it exists, then its right child if it exists.
  5. Repeat until the stack is empty, then reverse out and return it.

Dry run

The table traces the example tree. Each row shows the stack after one pop and its pushes, with the top on the right. The last row is the output before reversing.

StepStack after step (top on right)Popped nodeOutput so far
0[1]none[]
1[2, 3]1[1]
2[2, 8]3[1, 3]
3[2, 9]8[1, 3, 8]
4[2]9[1, 3, 8, 9]
5[4, 5]2[1, 3, 8, 9, 2]
6[4, 6, 7]5[1, 3, 8, 9, 2, 5]
7[4, 6]7[1, 3, 8, 9, 2, 5, 7]
8[4]6[1, 3, 8, 9, 2, 5, 7, 6]
9[]4[1, 3, 8, 9, 2, 5, 7, 6, 4]

Reversing the last output gives [4, 6, 7, 5, 2, 9, 8, 3, 1], which matches the expected answer.

Complexity

TimeO(n)
SpaceO(h) for the stack, O(n) in the worst case

Let n be the number of nodes. Each node is pushed once and popped once, and each pop does constant work, so the loop is O(n). The final reverse makes one more pass over the n values. The stack holds the pending left siblings along the current path plus at most two children of the node being processed, so its size is O(h), which is O(n) in the worst case.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if root is None:
            return []
        stack = [root]
        out = []
        while stack:
            node = stack.pop()
            out.append(node.val)
            # Push left first so right is popped first
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)
        # The output is root, right, left. Reverse it.
        out.reverse()
        return out

Common mistakes

  • result.append(node.val) placed before the two recursive calls. This gives root-first order. Move the append after both traverse(node.left) and traverse(node.right) return.
  • traverse(node.left, new ArrayList<>()) creates a fresh list for each call. The values vanish when the call returns. Pass the same shared list into every call.
  • traverse(node.left) called on a null node, or node.left read when node is null. Check for null at the top of traverse before touching any field.
  • stack.push(node.right) before stack.push(node.left) in the iterative version. Popping then gives root, left, right, and the reversed output is wrong. Push left first, then right.
  • Skipping the final reverse in the iterative version. Without it the output is root, right, left, which is the reversed postorder.
  • Returning a List<Integer> from the public method in Java or C#, where the starter needs int[]. Build the list inside helpers and convert to an array only at the top level.

Edge cases

  • root = [] (null root): return an empty list. The iterative version must check for null before pushing, because the loop would read node.val on a null node.
  • root = [1]: a single node returns [1]. The reverse step leaves a one-element list unchanged.
  • A left-leaning chain 1 -> 2 -> 3 (only left children): returns [3, 2, 1]. A right-leaning chain 1 -> 2 -> 3 also returns [3, 2, 1], because the order depends on position, not on which side is longer.
  • Negative and repeated values: a root of -1 with left child -2 and right child -1 returns [-2, -1, -1]. Nodes are placed by tree position, so equal values are never merged or reordered by value.
  • Maximum size of 100 nodes in a chain: the recursion depth is 100, which is well within the default call stack in all six languages.

Follow-ups interviewers ask

How do you remove the call stack from the recursive solution?
Use an explicit stack. Pop a node, record it, push its left child, then push its right child. Reverse the recorded list at the end. The time stays O(n), and the stack size stays O(h). This is the third approach on this page.
Can you traverse with O(1) extra space, not counting the output?
Yes, with Morris-style threading. You temporarily point the rightmost node of each left subtree back to its ancestor, walk the tree, and undo those links. The time is O(n) and the extra space is O(1). The code is error prone, so use it only when stack memory is the stated limit.
What if the tree is too large to hold the whole result in memory?
The reverse trick needs the full output before it can emit anything. To stream values, push each node twice, once unvisited and once marked as ready to emit, and emit a node when its second copy is popped. Memory is O(h) plus the stack of marked nodes, and values come out in postorder as they are ready.

Binary Tree Postorder Traversal FAQ

What is the time complexity of Binary Tree Postorder Traversal?

The recursive-with-shared-list and iterative solutions run in O(n) time, where n is the number of nodes. Each node is visited once and does constant work. The list concatenation approach is O(n^2) on a skewed tree because it copies data at every level.

Why use depth-first recursion for Binary Tree Postorder Traversal?

Postorder means children before the node. A recursive call returns only after its whole subtree is processed, so appending after the two calls produces the right order. The explicit stack version does the same job without the call stack.

Can Binary Tree Postorder Traversal be solved in O(1) extra space?

Not with a plain stack, which needs O(h) space, and h can be n on a skewed tree. Morris-style traversal reaches O(1) extra space by threading temporary pointers through the tree and restoring them afterward. It still runs in O(n) time but is harder to write correctly.

Why does the iterative postorder solution reverse its output?

Pushing left first and popping gives root, then right side, then left side. That is postorder read backwards. Reversing the list fixes the order in one O(n) pass.

What is the difference between preorder and postorder traversal?

Preorder records the node before its children, so the root comes first. Postorder records the node after both children, so the root comes last. The code differs only in where the append sits.

Asked at

See which companies ask this — Pro

Practise it