← Back to Algorithms, page 3

algorithms-0051 · Easy fresher

Binary tree traversals: write preorder, inorder and postorder both recursively and with an explicit stack, and explain when each order is useful.

Preorder visits node, left, right; inorder visits left, node, right; postorder visits left, right, node. Recursion is three lines each. The iterative versions use a stack: inorder pushes the left spine then pops and turns right, preorder pushes right before left, and postorder reverses a node-right-left preorder. All are O(n) time and O(h) space, where h is the tree height.

Full answer

Problem

Given the root of a binary tree, return its values in preorder, inorder and postorder. Write each one twice: recursively and iteratively.

Example: for the tree 4 -> (2 -> 1, 3), (6 -> 5, 7), preorder is [4, 2, 1, 3, 6, 5, 7], inorder is [1, 2, 3, 4, 5, 6, 7] and postorder is [1, 3, 2, 5, 7, 6, 4].

Constraints: up to 10^5 nodes; the tree may be a single long chain, so recursion depth can reach n.

Brute force

The recursive definitions are the baseline: inorder(n) = inorder(n.left) + [n.val] + inorder(n.right). They are correct and O(n) visits, but list concatenation copies results (O(n^2) in the worst case for a chain), and Python's default recursion limit of 1,000 breaks on deep trees.

Optimal approach

Use an explicit stack and append into one output list.

  • Inorder: push nodes while walking left; pop one, record it, then move to its right child.
  • Preorder: pop a node, record it, push its right child, then its left child, so the left is processed first.
  • Postorder: run preorder with the child order swapped (node, right, left) and reverse the output.

Why it works

The stack holds exactly the ancestors whose own value or right subtree is still pending, which is what the call stack holds in the recursive version. In inorder, a node is popped only after its entire left subtree has been recorded, which matches "left, node, right". Reversing node-right-left gives left-right-node, which is postorder.

Complexity

Each node is pushed and popped once: O(n) time. The stack holds at most one root-to-leaf path: O(h) space, which is O(log n) for a balanced tree and O(n) for a chain.

Code

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


def preorder(root):
    return [] if not root else [root.val] + preorder(root.left) + preorder(root.right)


def inorder(root):
    return [] if not root else inorder(root.left) + [root.val] + inorder(root.right)


def postorder(root):
    return [] if not root else postorder(root.left) + postorder(root.right) + [root.val]


def inorder_iterative(root):
    """Explicit stack: no recursion limit on deep trees. O(n) time, O(h) space."""
    out, stack, node = [], [], root
    while stack or node:
        while node:                      # go as far left as possible
            stack.append(node)
            node = node.left
        node = stack.pop()
        out.append(node.val)
        node = node.right
    return out


def preorder_iterative(root):
    out, stack = [], [root] if root else []
    while stack:
        node = stack.pop()
        out.append(node.val)
        if node.right:
            stack.append(node.right)     # pushed first so left is processed first
        if node.left:
            stack.append(node.left)
    return out


def postorder_iterative(root):
    """Reverse of a root-right-left preorder."""
    out, stack = [], [root] if root else []
    while stack:
        node = stack.pop()
        out.append(node.val)
        if node.left:
            stack.append(node.left)
        if node.right:
            stack.append(node.right)
    return out[::-1]


if __name__ == "__main__":
    #        4
    #      2   6
    #     1 3 5 7
    t = TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode(6, TreeNode(5), TreeNode(7)))
    assert preorder(t) == preorder_iterative(t) == [4, 2, 1, 3, 6, 5, 7]
    assert inorder(t) == inorder_iterative(t) == [1, 2, 3, 4, 5, 6, 7]
    assert postorder(t) == postorder_iterative(t) == [1, 3, 2, 5, 7, 6, 4]
    assert inorder(None) == inorder_iterative(None) == preorder_iterative(None) == []
    deep = None
    for v in range(5000):                # a 5,000-deep chain: recursion would fail
        deep = TreeNode(v, deep)
    assert inorder_iterative(deep) == list(range(5000))
    print("all tests passed")

Save as b51_traversals.py and run python3 b51_traversals.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty tree returns []. A single node. A chain of 5,000 nodes (the iterative version handles it; the recursive one would exceed the default limit). Duplicate values do not change the order.

Pattern

Depth-first traversal with an explicit stack. Inorder of a BST gives sorted order (used in validation and kth-smallest); preorder is the natural order to serialize or copy a tree; postorder computes values that depend on children, such as heights, sizes and deletion.

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


def preorder(root):
    return [] if not root else [root.val] + preorder(root.left) + preorder(root.right)


def inorder(root):
    return [] if not root else inorder(root.left) + [root.val] + inorder(root.right)


def postorder(root):
    return [] if not root else postorder(root.left) + postorder(root.right) + [root.val]


def inorder_iterative(root):
    """Explicit stack: no recursion limit on deep trees. O(n) time, O(h) space."""
    out, stack, node = [], [], root
    while stack or node:
        while node:                      # go as far left as possible
            stack.append(node)
            node = node.left
        node = stack.pop()
        out.append(node.val)
        node = node.right
    return out


def preorder_iterative(root):
    out, stack = [], [root] if root else []
    while stack:
        node = stack.pop()
        out.append(node.val)
        if node.right:
            stack.append(node.right)     # pushed first so left is processed first
        if node.left:
            stack.append(node.left)
    return out


def postorder_iterative(root):
    """Reverse of a root-right-left preorder."""
    out, stack = [], [root] if root else []
    while stack:
        node = stack.pop()
        out.append(node.val)
        if node.left:
            stack.append(node.left)
        if node.right:
            stack.append(node.right)
    return out[::-1]


if __name__ == "__main__":
    #        4
    #      2   6
    #     1 3 5 7
    t = TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode(6, TreeNode(5), TreeNode(7)))
    assert preorder(t) == preorder_iterative(t) == [4, 2, 1, 3, 6, 5, 7]
    assert inorder(t) == inorder_iterative(t) == [1, 2, 3, 4, 5, 6, 7]
    assert postorder(t) == postorder_iterative(t) == [1, 3, 2, 5, 7, 6, 4]
    assert inorder(None) == inorder_iterative(None) == preorder_iterative(None) == []
    deep = None
    for v in range(5000):                # a 5,000-deep chain: recursion would fail
        deep = TreeNode(v, deep)
    assert inorder_iterative(deep) == list(range(5000))
    print("all tests passed")

Recursive one-liners plus stack-based versions that survive deep trees; a 5,000-node chain is part of the tests.

Complexity

Time: O(n). Space: O(h) stack, h = tree height. The recursive list-concatenation version is O(n^2) on a chain because of copying; appending into one list avoids that.

By level

Fresher: Writes the recursive versions and the iterative inorder, and traces them on a small tree. Explains why the stack is needed for deep trees.

Mid: Writes all three iterative versions cleanly and states O(h) space with best and worst case heights. Connects each order to a real use such as BST sorting, serialization or computing subtree sizes.

Senior: Discusses Morris traversal for O(1) space and its temporary pointer rewiring, and when that trade-off is acceptable. Notes how traversal order affects cache behaviour and how iterators over trees expose lazy traversal in library code.

Key points

  • Preorder node-left-right, inorder left-node-right, postorder left-right-node
  • The explicit stack mirrors the call stack
  • Push right before left for iterative preorder
  • Postorder is a reversed node-right-left preorder
  • O(n) time and O(h) space

Common mistakes

  • Pushing left before right in iterative preorder
  • Forgetting to move to the right child after popping in inorder
  • Relying on recursion for trees that can be 10^5 deep
  • Building results with list concatenation in a loop

Follow-ups

  • How would you do inorder in O(1) extra space (Morris traversal)?
  • Which traversal would you use to delete a tree, and why?
  • How do you rebuild a tree from preorder and inorder?

Tips

  • Draw a 7-node tree and write all three orders before coding
  • State the height-based space bound, not just O(n)
  • Mention the recursion limit for Python

Evaluation rubric

  • Correct three orders
  • Working iterative version
  • Correct complexity in terms of height
  • Knows a use case for each order