Binary tree postorder traversal solution explained

Binary tree postorder traversal visits both subtrees before the node itself: left subtree, right subtree, then the node. Recursively it is trivial; iteratively, the simplest trick is to walk root, right, left with a stack and reverse the result, and the version interviewers like best uses one stack plus a pointer to the last node emitted, so a parent is only output after its right subtree is finished. All versions run in O(n) time and O(h) extra space.

By Published 7 min read

The problem in plain words

Given the root of a binary tree, return its values in postorder: a node's value appears only after every value in its left subtree and then every value in its right subtree. The root therefore always comes last. An empty tree returns an empty list.

        6
       / \
      3   9
     / \    \
    1   5    11
       /
      4

Postorder: [1, 4, 5, 3, 11, 9, 6]
Our example tree and its postorder

Leaves come out first, in left-to-right order, each parent right after its last child: 1, then 4 and its parent 5, then 3, whose subtrees are now both done. On the right, 11 and then 9. The root 6 closes the list.

Why this order matters

Postorder is the order of any computation where a node needs its children's answers first: a tree's height, the size of each subtree, deleting a tree without leaving dangling children, evaluating an expression tree, or the greedy covering in Binary Tree Cameras. That is why interviewers ask for it iteratively. Unlike preorder, you cannot output a node when you first meet it, so you need a way to know when its right side is finished.

Baseline: recursion

class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def postorder_recursive(root):
    out = []

    def visit(node):
        if node is None:
            return
        visit(node.left)
        visit(node.right)
        out.append(node.val)   # root last

    visit(root)
    return out
Python, recursive. O(n) time, O(h) call stack.

Same cost as any depth-first walk, and the same weakness: a tree shaped like a long chain recurses once per node, which can exceed the language's recursion limit long before memory runs out.

Iterative shortcut: reverse a mirrored preorder

Postorder is left, right, root. Read backwards it is root, right, left, which is just preorder with the children swapped. So run the stack version of preorder, push the left child before the right one this time, and reverse the list at the end.

def postorder_reversed(root):
    out = []
    stack = [root] if root else []
    while stack:
        node = stack.pop()
        out.append(node.val)        # produces root, right, left
        if node.left:
            stack.append(node.left)
        if node.right:
            stack.append(node.right)
    out.reverse()                   # left, right, root
    return out
Python, two-phase: collect root-right-left, then reverse. O(n) time, O(n) for the output before reversing.

It is correct and quick to write, and many interviewers accept it. The catch: it does not really visit nodes in postorder. You only learn the order once the whole tree is read. If the follow-up is "process each node as soon as its children are done", for example to free memory as you go, you need the next version.

True iterative postorder: one stack and a last-emitted pointer

Slide down the left edge from the current node, pushing every node. When you cannot go further left, look at the top of the stack without popping it. If it has a right child that you have not just finished, go into that right subtree next. Otherwise both its subtrees are done: emit it, pop it, and remember it as the last emitted node. That memory is what tells a parent, on its next turn at the top, that its right subtree is complete.

def postorder_one_stack(root):
    out, stack = [], []
    node, last = root, None         # last = the node most recently emitted
    while node or stack:
        if node:                    # slide down the left edge
            stack.append(node)
            node = node.left
            continue
        top = stack[-1]
        if top.right and top.right is not last:
            node = top.right        # right subtree not done yet
        else:
            out.append(top.val)     # both subtrees done
            last = stack.pop()
    return out
Python, one stack. O(n) time, O(h) stack. Nodes are emitted in true postorder.
function postorderOneStack(root) {
  const out = [];
  const stack = [];
  let node = root;
  let last = null; // most recently emitted node
  while (node || stack.length > 0) {
    if (node) {
      stack.push(node);
      node = node.left;
      continue;
    }
    const top = stack[stack.length - 1];
    if (top.right && top.right !== last) {
      node = top.right;
    } else {
      out.push(top.val);
      last = stack.pop();
    }
  }
  return out;
}
JavaScript, one stack. Compares node objects, so duplicate values are safe.

Trace on the example. Push 6, 3, 1. Top is 1, no right child: emit 1. Top is 3; its right child 5 was not just emitted, so move to 5 and push 5, 4. Emit 4. Top is 5, no right child: emit 5. Top is 3 again; its right child 5 is the last emitted, so emit 3. Top is 6; go right to 9, push 9; 9 has right child 11, push it, emit 11, then 9, then 6.

Complexity

n nodes, height h
ApproachTimeExtra spaceVisits in real postorder?
RecursionO(n)O(h) call stackYes
Mirrored preorder, then reverseO(n)O(h) stack plus the full output before reversingNo, only the final list is
One stack with last-emitted pointerO(n)O(h)Yes
n nodes, height h. Scroll sideways on a small screen.

A Morris-style O(1) space postorder exists, but it needs to output reversed segments of right edges and is rarely expected. Mention that it exists if asked about constant space, and offer the one-stack version as the practical answer.

Edge cases to test

  • Empty tree and single node.
  • A chain of only left children (output is the chain from the bottom up) and a chain of only right children.
  • A node with only a right child, which exercises the "go right first" branch.
  • Many equal values, which breaks any version that compares values instead of node identity.

Common mistakes

  • In the reverse trick, pushing right before left, which yields preorder reversed instead of postorder.
  • In the one-stack version, popping the top before checking its right child, which loses the parent.
  • Comparing top.right.val == last.val instead of the nodes themselves; equal values make the loop skip a subtree.
  • Pointing node back at the emitted node, or at its left child, after emitting. node must stay empty so the next turn looks at the stack, otherwise the same subtree is pushed again and the loop never ends.
  • Calling the reverse trick a true postorder visit when the interviewer asks for per-node processing.

How to explain it out loud

Fictional example

Explaining the one-stack version
Candidate
In postorder a node waits for both children. With a stack, the hard part is knowing whether I am coming back to a node from its left side or its right side.
Candidate
So I keep a pointer to the last node I output. When the top of the stack has a right child that is not that node, I still owe its right subtree, so I go there. Otherwise I output it.
Candidate
Each node is pushed and popped once: linear time, and the stack never holds more than one path from the root.
Interviewer
Is there a quicker way to write it?
Candidate
Yes, build root, right, left with a simple stack and reverse it. It gives the right list, but it does not let me act on a node when its children finish.

Start with Binary Tree Preorder Traversal if the stack trick is new; this page builds on it. Postorder's last element is always the root, which is the key fact in Construct Binary Tree from Inorder and Postorder. For a real bottom-up computation in postorder, try Binary Tree Cameras. The coding problems hub lists the rest.

Practicing with Natively

Postorder bugs are easiest to find by tracing a small tree by hand. In practice sessions, Natively can take a screenshot of a tree problem on your Mac or Windows screen, walk through the one-stack trace step by step, and point out where a value comparison would break on duplicates. It keeps a transcript of your mock interview, so you can hear whether your explanation of the last-emitted pointer was clear.

Questions people ask

What is postorder traversal of a binary tree?

Visiting a node only after both of its subtrees: the whole left subtree, then the whole right subtree, then the node. The root always comes last.

How do you do postorder traversal iteratively?

Either build root, right, left with a stack and reverse it, or use one stack plus a pointer to the last node output, emitting the top node only when its right child is empty or was just output.

What is the complexity of iterative postorder traversal?

O(n) time and O(h) extra space for the stack, where h is the tree's height.

Is reversing a modified preorder a real postorder traversal?

It produces the correct list, but nodes are not processed in postorder while walking. If you must act on each node as soon as its children finish, use the one-stack method.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP