Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

Binary Trees & Traversals

Preorder, inorder, postorder and level order, and thinking recursively about trees.

Ask a binary tree for its longest path and the naive answer tries every pair of nodes. Ask each subtree instead for one number, its height, and the answer falls out of a single pass that visits every node once. This lesson builds that habit: the four traversal orders, how to run them with or without recursion, how to rebuild a tree from two of them, and how to decide what each subtree should report to its parent.

What you’ll learn

  • Define binary trees recursively, prove the counting facts (n−1n-1 edges, n+1n+1 empty pointers, h≥⌊log⁡2n⌋h\ge\lfloor\log_2 n\rfloor), and store a tree with pointers or, when it is complete, in an array.
  • Implement preorder, inorder, postorder and level order recursively and iteratively, in Θ(n)\Theta(n) time with O(h)O(h) or O(w)O(w) extra space.
  • Rebuild a binary tree from its preorder and inorder in O(n)O(n), and explain why preorder and postorder do not determine it.
  • Solve height, diameter, balance and path problems with one postorder pass in which each subtree reports what its parent needs.
  • Recognize tree problems, choose the traversal order by data flow, and avoid stack overflows on degenerate trees.

Binary trees, recursively

A binary tree is defined recursively: it is either empty, or a node holding a key together with two binary trees, its left and right subtrees. Algorithms follow the same shape: handle the empty tree, then combine a node with the answers for its two subtrees. Proofs follow it too, by structural induction: prove a statement for the empty tree, then for a node assuming it holds for both subtrees.

A few counting facts are used constantly. Write nn for the number of nodes and hh for the height, the number of edges on the longest root-to-leaf path, with −1-1 for the empty tree.

DerivationProofs
  1. 2n−(n−1)=n+12n-(n-1)=n+1

    Edges and empty pointers. Every node except the root has exactly one parent, so exactly n−1n-1 of the 2n2n child pointers lead to a node, and those are the edges. The rest are empty:

  2. n ≤ ∑d=0h2d=2h+1−1⟹h ≥ ⌈log⁡2(n+1)⌉−1=⌊log⁡2n⌋n\ \le\ \sum_{d=0}^{h}2^d=2^{h+1}-1\quad\Longrightarrow\quad h\ \ge\ \lceil\log_2(n+1)\rceil-1=\lfloor\log_2 n\rfloor

    Height. Depth dd holds at most 2d2^d nodes, since each node has at most two children. Summing over the depths 0,…,h0,\dots,h, and using that hh is an integer:

  3. 2i=(i+ℓ)−1⟹ℓ=i+12i=(i+\ell)-1\quad\Longrightarrow\quad \ell=i+1

    Full trees. Count the edges twice: each of the ii internal nodes has two children, and every node but the root has one parent. With ℓ\ell leaves:

Representations. The usual one is linked: each node stores its key and two pointers, sometimes a parent pointer too. A complete tree needs no pointers at all: store it level by level in an array, and the children of index ii sit at 2i+12i+1 and 2i+22i+2, its parent at ⌊(i−1)/2⌋\lfloor(i-1)/2\rfloor. That is how a binary heap lives; segment trees often use the 1-indexed variant, with children 2i2i and 2i+12i+1. For other shapes the array layout wastes space: a path of height hh would occupy 2h+1−12^{h+1}-1 cells.

A rooted tree with any number of children per node becomes a binary tree under the left-child, right-sibling representation: the left pointer leads to the first child, the right pointer to the next sibling. Much of this lesson therefore applies to general trees as well.

Think first A binary tree has 1,000 nodes. How short can it be, and how tall?

At least ⌊log⁡21000⌋=9\lfloor\log_2 1000\rfloor=9, since height 8 leaves room for only 29−1=5112^9-1=511 nodes; a complete tree achieves 9. At most 999999, when the tree is a single path. Every algorithm whose cost is O(h)O(h), such as a BST search, lives somewhere in that range, which is why balancing matters.

Four traversals, two ways to run them

The three depth-first orders differ only in where the visit sits among the two recursive calls: before them (preorder), between them (inorder) or after them (postorder). Level order is breadth-first: it keeps a queue and visits depth 0, then depth 1, and so on.

python
def preorder(x, out):
    if x:
        out.append(x.key); preorder(x.left, out); preorder(x.right, out)

def inorder(x, out):
    if x:
        inorder(x.left, out); out.append(x.key); inorder(x.right, out)

def postorder(x, out):
    if x:
        postorder(x.left, out); postorder(x.right, out); out.append(x.key)

There is one call per node and one per empty pointer, 2n+12n+1 calls of O(1)O(1) work each: Θ(n)\Theta(n) time. The call stack holds one frame per node on the current root path, so the extra space is O(h)O(h): Θ(log⁡n)\Theta(\log n) for a balanced tree, Θ(n)\Theta(n) for a path.

python
from collections import deque

def inorder_iter(root):
    out, stack, x = [], [], root
    while stack or x:
        while x:                          # push the left spine of x
            stack.append(x)
            x = x.left
        x = stack.pop()                   # leftmost node not yet visited
        out.append(x.key)
        x = x.right                       # then walk its right subtree
    return out

def level_order(root):
    levels, q = [], deque([root] if root else [])
    while q:
        level = []
        for _ in range(len(q)):           # exactly the nodes of one depth
            x = q.popleft()
            level.append(x.key)
            if x.left: q.append(x.left)
            if x.right: q.append(x.right)
        levels.append(level)
    return levels

The explicit stack holds the nodes whose left subtree is being walked and whose own visit is still due. Iterative preorder pops a node, visits it, and pushes its right child before its left; iterative postorder can run the mirror preorder (node, right, left) and reverse the output. The iterative depth-first versions were checked against the recursive ones on 3,000 random trees.

Predict before you look

Level order runs on a perfect binary tree with 10231023 nodes (height 9). What is the largest number of nodes waiting in the queue at any moment?

Show the answer

512 nodes

The queue peaks when the last node of depth 8 has been processed: all 29=5122^9=512 nodes of the bottom level are waiting, half the tree. A depth-first walk of the same tree never holds more than 10 nodes, one per level of the current path. Level order needs O(w)O(w) extra space, where ww is the widest level, and depth-first order O(h)O(h); on bushy trees depth-first is far leaner, unless you need the levels.

Rebuilding a tree from two traversals

One traversal does not pin down a tree: label each of the five binary trees with three nodes in preorder, and all five have preorder 1 2 3. Two traversals can, as long as one of them is the inorder.

DerivationProof, by induction on the number of nodes
  1. inorder=a0⋯ak−1⏟left subtree  r  ak+1⋯an−1⏟right subtree\text{inorder}=\underbrace{a_0\cdots a_{k-1}}_{\text{left subtree}}\ \ r\ \ \underbrace{a_{k+1}\cdots a_{n-1}}_{\text{right subtree}}

    The empty sequences give the empty tree. Otherwise the first key rr of the preorder is the root. Since keys are distinct, rr occurs once in the inorder, at some position kk, and inorder lists the left subtree, then rr, then the right subtree:

  2. preorder=r  b1⋯bk⏟left subtree  bk+1⋯bn−1⏟right subtree\text{preorder}=r\ \ \underbrace{b_1\cdots b_k}_{\text{left subtree}}\ \ \underbrace{b_{k+1}\cdots b_{n-1}}_{\text{right subtree}}

    So the left subtree has exactly kk nodes, and the preorder lists the root, then the whole left subtree, then the whole right subtree:

  3. T(n)=T(k)+T(n−1−k)+O(1)⟹T(n)=O(n)T(n)=T(k)+T(n-1-k)+O(1)\quad\Longrightarrow\quad T(n)=O(n)

    Each subtree has fewer than nn nodes, and we now hold its preorder and its inorder, so by induction each subtree is determined, and with it the whole tree. Looking kk up in a hash map of inorder positions makes each step O(1)O(1):

python
def build(preorder, inorder):
    pos = {key: i for i, key in enumerate(inorder)}   # keys must be distinct
    it = iter(preorder)
    def make(lo, hi):                     # the subtree whose inorder is inorder[lo:hi]
        if lo == hi:
            return None
        key = next(it)                    # preorder lists that subtree's root first
        node = Node(key)
        node.left = make(lo, pos[key])
        node.right = make(pos[key] + 1, hi)
        return node
    return make(0, len(inorder))

The recursion consumes the preorder in exactly its own order (root, left subtree, right subtree), so one iterator replaces all index arithmetic. Scanning the inorder for each root instead of using pos costs Θ(n2)\Theta(n^2) in the worst case, a path. Checked by rebuilding 3,000 random trees from their traversals.

Inorder plus postorder works the same way (the root is last in postorder), and so does inorder plus level order. Without the inorder, information is lost. Preorder 1 2 with postorder 2 1 fits two trees: 2 can be the left or the right child of 1.

In general, preorder and postorder together fix every parent–child relation and the order of siblings, but not which side a lone child hangs on. If kk nodes have exactly one child, 2k2^k binary trees share both sequences, so for full binary trees (k=0k=0) the pair does determine the tree.

Check your understanding

A binary tree with distinct keys has preorder 4 2 1 3 6 5 7 and inorder 1 2 3 4 5 6 7. What is its postorder?

  1. 1 2 3 5 6 7 4
  2. 7 5 6 3 1 2 4
  3. 1 3 2 5 7 6 4
  4. 2 1 3 6 5 7 4
Show the answer

C. 1 3 2 5 7 6 4

The root is 4, first in the preorder. In the inorder, 1 2 3 lie to its left and 5 6 7 to its right. The left subtree's preorder is 2 1 3, so its root is 2 with children 1 and 3; likewise the right subtree is 6 with children 5 and 7. Postorder lists each subtree before its root: 1 3 2, then 5 7 6, then 4.

Thinking recursively: what should a subtree report?

Most binary-tree problems are solved by one postorder pass: get the answers for the two subtrees, then combine them at the node. The design question is what each subtree must report to its parent. Size and height need one number each: size(x)=1+size(L)+size(R)\text{size}(x)=1+\text{size}(L)+\text{size}(R), and h(x)=1+max⁡(h(L),h(R))h(x)=1+\max\big(h(L),h(R)\big) with h(∅)=−1h(\varnothing)=-1. The diameter shows the pattern at its best.

DerivationThe diameter in one pass
  1. u ↗ ⋯ ↗ t ↘ ⋯ ↘ vu\ \nearrow\ \cdots\ \nearrow\ t\ \searrow\ \cdots\ \searrow\ v

    Every path has a top. A path in a tree climbs to its highest node tt and then descends; it cannot descend and climb again, since that would revisit a node. Below tt it enters at most two of tt's child subtrees, one on each side.

  2. longest path with top t  =  (h(t.left)+1)+(h(t.right)+1)\text{longest path with top } t\;=\;\big(h(t.\text{left})+1\big)+\big(h(t.\text{right})+1\big)

    The best path with top tt. Each side contributes one edge into the child plus at most that child's height, and an absent side contributes nothing, which the convention h(∅)=−1h(\varnothing)=-1 handles automatically. Descending to a deepest node on each side attains the bound:

  3. diam⁡(T)=max⁡t∈T(h(t.left)+h(t.right)+2)\operatorname{diam}(T)=\max_{t\in T}\Big(h(t.\text{left})+h(t.\text{right})+2\Big)

    Maximize over the top. Every path has exactly one top, so the diameter is the best value over all nodes, and the heights it needs are exactly what the postorder pass computes anyway:

  4. ∑xsize⁡(x)=∑v(depth⁡(v)+1)=n(n+1)2  on a path\sum_{x}\operatorname{size}(x)=\sum_{v}\big(\operatorname{depth}(v)+1\big)=\frac{n(n+1)}{2}\ \text{ on a path}

    Cost. The pass does O(1)O(1) work per node: Θ(n)\Theta(n). Calling a fresh height function at every node instead costs the sum of all subtree sizes, every node counted once per ancestor:

python
def diameter_and_balance(root):
    best, balanced = 0, True
    def height(x):                        # postorder: both children first
        nonlocal best, balanced
        if x is None:
            return -1
        hl, hr = height(x.left), height(x.right)
        best = max(best, hl + hr + 2)     # longest path whose top node is x
        if abs(hl - hr) > 1:
            balanced = False              # x breaks the height-balance rule
        return 1 + max(hl, hr)            # what the parent needs
    height(root)
    return best, balanced

The function returns what the parent needs, the height, and records what the problem asks for on the side. Checked against a breadth-first search from every node on 3,000 random trees.

The same habit solves a whole family of problems in O(n)O(n):

  • Maximum path sum, keys possibly negative: return the best downward path from the node, with each child's contribution clamped at 0, and record key+left gain+right gain\text{key}+\text{left gain}+\text{right gain} as a candidate.
  • A root-to-leaf path with sum SS: preorder, passing the remaining sum down to the children.
  • Symmetric tree: compare the left subtree with the mirror image of the right one, recursing on the pairs (left.left, right.right) and (left.right, right.left).
  • Lowest common ancestor of uu and vv. In a BST, walk down from the root until the two keys split: the first node with u≤key≤vu\le\text{key}\le v is the answer, in O(h)O(h). In a general tree, a postorder pass reports whether each subtree contains uu or vv; the lowest node that has one of them on each side, or is one of them with the other below it, is the answer: O(n)O(n) per query.
Think first For the maximum path sum, why must the recursion return the best downward path from a node rather than the best path anywhere in its subtree?

Only a downward path can be extended through the parent: a path that already bends at a node uses both of that node's sides and cannot continue upward. So each call returns the best path starting at its node, which is what the parent can use, and records the best bending path on the side. When a node needs several such numbers from each child, the pass returns a tuple per subtree, and that is dynamic programming on trees.

Recognizing it

Reach for a tree traversal when:

  • the input is a tree or a hierarchy: nodes with child pointers, a parent array, nested folders, an org chart, an arithmetic expression, a thread of replies;
  • the question concerns every subtree ("for each node, …"), root-to-leaf paths, or levels ("by depth", "nearest to the root", "seen from the side");
  • nn goes up to about 10510^5 or 10610^6, so the intended solution is a single O(n)O(n) pass.

Then pick the order by data flow: postorder when a node needs its children's answers, preorder when children need something from their ancestors (a depth, a running sum, the path so far), inorder when a BST's sorted order matters, level order when depth or distance from the root does.

Problem (in brief)Key ideaCost
Longest path between any two nodesReturn the height; record h(L)+h(R)+2h(L)+h(R)+2 at every nodeO(n)O(n)
Largest sum along any path, keys may be negativeReturn the best downward path, children clamped at 0; record key plus both gainsO(n)O(n)
The node seen at each depth from the right sideLevel order; keep the last node of each levelO(n)O(n)
Rebuild a tree from its preorder and inorderRoot first in preorder; split the inorder at it; hash map of positionsO(n)O(n)
Turn a tree into a string and backPreorder with a marker per empty pointer: 2n+12n+1 tokensO(n)O(n)
Five common shapes of a tree problem; each is one traversal with the right return value.
Check your understanding

You need the depth of the shallowest leaf in a huge, lopsided tree, touching as few nodes as possible. Which traversal fits?

  1. Postorder, combining the children's minimum depths
  2. Level order, stopping at the first leaf it dequeues
  3. Inorder, since it reaches the leftmost leaf first
  4. Preorder, reporting the depth of the first leaf it reaches
Show the answer

B. Level order, stopping at the first leaf it dequeues

Level order dequeues nodes in order of depth, so the first leaf it dequeues is a shallowest one, and it stops before dequeuing anything deeper. A depth-first order may dive down a long branch first and must finish every branch before it can be sure.

Key takeaways

  • A binary tree is empty or a node with two binary subtrees. With n≥1n\ge1 nodes it has n−1n-1 edges and n+1n+1 empty pointers, and its height is at least ⌊log⁡2n⌋\lfloor\log_2 n\rfloor.
  • Preorder, inorder and postorder differ only in when a node is visited. Recursively or with an explicit stack they take Θ(n)\Theta(n) time and O(h)O(h) extra space; level order uses a queue and O(w)O(w) space.
  • Inorder together with preorder, postorder or level order determines a tree with distinct keys, rebuilt in O(n)O(n) with a hash map of positions; preorder with postorder leaves 2k2^k trees when kk nodes have one child.
  • Most tree problems are one postorder pass in which each subtree returns what its parent needs (a height, a best downward path) while the answer is recorded on the side: diameter, balance and maximum path sum all take O(n)O(n).
  • Recursion depth equals the height: when a tree can degenerate into a path, use an explicit stack or raise the limits.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A binary tree has nn nodes. It is serialized in preorder, writing each key and a marker for every empty child pointer. How many tokens are written?

  1. 2n2n
  2. n+1n+1
  3. 2n+12n+1
  4. 3n3n
Show the answer

C. 2n+12n+1

nn keys plus n+1n+1 markers: of the 2n2n child pointers, n−1n-1 lead to nodes and n+1n+1 are empty. The markers make the preorder alone sufficient, because they say exactly where each subtree ends; reading the tokens back with the same recursion rebuilds the tree.

Question 2

Which pair of traversals does not always determine a binary tree with distinct keys?

  1. Preorder and postorder
  2. Preorder and inorder
  3. Postorder and inorder
  4. Level order and inorder
Show the answer

A. Preorder and postorder

Without the inorder, a node with a single child does not reveal which side the child hangs on: preorder 1 2 and postorder 2 1 fit both trees in which 2 is a child of 1. With kk single-child nodes, 2k2^k trees share both sequences; for full binary trees the pair does suffice.

Question 3

A diameter routine calls a fresh height function at every node. On a path of nn nodes, how does it compare with the one-pass version?

  1. Θ(nlog⁡n)\Theta(n\log n) against Θ(n)\Theta(n)
  2. Both are Θ(n)\Theta(n), since every node is visited
  3. Θ(n2)\Theta(n^2) against Θ(n)\Theta(n)
  4. Θ(n2)\Theta(n^2) against Θ(nlog⁡n)\Theta(n\log n)
Show the answer

C. Θ(n2)\Theta(n^2) against Θ(n)\Theta(n)

A fresh height call at node xx visits all of xx's subtree, so the total is the sum of all subtree sizes: n+(n−1)+⋯+1=n(n+1)/2n+(n-1)+\cdots+1=n(n+1)/2 on a path. The one-pass version returns each height to the parent and does O(1)O(1) work per node.

Question 4

The iterative inorder traversal (push the left spine, pop, visit, go right) runs on a BST built by inserting 1,2,…,n1, 2, \dots, n in increasing order. What is the largest size its stack reaches?

  1. nn, the height plus one
  2. 11
  3. About log⁡2n\log_2 n
  4. About n/2n/2
Show the answer

B. 11

The tree is a path of right children. No node has a left spine, so the loop pushes one node, pops it, visits it and moves right: the stack never holds more than one node. Recursive inorder on the same tree is nn calls deep, because each call waits for its right subtree; the iterative version turns that last call into a loop. Inserting in decreasing order builds a left path, and then the stack does reach nn.

Question 5

In the BST built by inserting 8, 3, 10, 1, 6, 14, 4, 7, 13, what is the lowest common ancestor of 4 and 7?

  1. 8, the root
  2. 3
  3. 4
  4. 6
Show the answer

D. 6

Walk down from the root: 4 and 7 are both smaller than 8, so go left to 3; both are larger than 3, so go right to 6; and 4≤6≤74\le6\le7, so the paths to 4 and 7 split here. 4 and 7 are the two children of 6.

Go deeper

Further reading

  • D. E. Knuth, The Art of Computer Programming, vol. 1: Fundamental Algorithms, 3rd ed. (Addison-Wesley, 1997), section 2.3.
  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 10 (representing rooted trees) and section 12.1.
  • A. Laaksonen, Competitive Programmer's Handbook (2018, free online), chapter 14.