Notes
All notes

Binary Trees and Traversals (DSA #9)

Arrays and lists are linear; real data is often hierarchical. A file system, the HTML DOM, an arithmetic expression, a company org chart — all are trees. A binary tree is the simplest hierarchical structure: each node has at most two children. Nearly every tree problem reduces to one skill: walking the tree in the right order, and doing the right thing at each node.

This chapter defines tree terminology, then covers the four traversals — preorder, inorder, postorder, and level-order — both recursively and iteratively, and the classic problems built on them.

Terminology

A binary tree uses at most two children:

class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.66cm, font=\small\bfseries, inner sep=0pt},
  a/.style={->, thick}]
  \node[n, fill=orange!28] (r) at (0,0) {1};
  \node[n, fill=blue!12] (l) at (-1.8,-1.1) {2};
  \node[n, fill=blue!12] (rr) at (1.8,-1.1) {3};
  \node[n, fill=green!16] (ll) at (-2.7,-2.2) {4};
  \node[n, fill=green!16] (lr) at (-0.9,-2.2) {5};
  \node[n, fill=green!16] (rl) at (0.9,-2.2) {6};
  \draw[a] (r) -- (l); \draw[a] (r) -- (rr);
  \draw[a] (l) -- (ll); \draw[a] (l) -- (lr);
  \draw[a] (rr) -- (rl);
  \node[font=\scriptsize\ttfamily, text=black!60] at (-2.7,-2.7) {leaf};
\end{tikzpicture}

A tree with \(n\) nodes has \(n - 1\) edges, and its height is between \(\log_2 n\) (balanced) and \(n - 1\) (a degenerate chain).

The four traversals

All four visit every node once — \(O(n)\) time. They differ in when they process a node relative to its children.

Preorder (node → left → right). Process the node before its subtrees. Used to copy a tree, serialize it, or prefix an expression.

def preorder(node, out):
    if not node:
        return
    out.append(node.val)
    preorder(node.left, out)
    preorder(node.right, out)

Inorder (left → node → right). Process the node between its subtrees. On a binary search tree this yields values in sorted order (Chapter 10).

def inorder(node, out):
    if not node:
        return
    inorder(node.left, out)
    out.append(node.val)
    inorder(node.right, out)

Postorder (left → right → node). Process the node after its subtrees — the order you need to delete a tree (children before parents) or evaluate an expression.

def postorder(node, out):
    if not node:
        return
    postorder(node.left, out)
    postorder(node.right, out)
    out.append(node.val)
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.66cm, font=\small\bfseries, inner sep=0pt},
  a/.style={->, thick}]
  \node[n, fill=orange!28] (r) at (0,0) {1};
  \node[n, fill=blue!12] (l) at (-1.8,-1.1) {2};
  \node[n, fill=blue!12] (rr) at (1.8,-1.1) {3};
  \node[n, fill=green!16] (ll) at (-2.7,-2.2) {4};
  \node[n, fill=green!16] (lr) at (-0.9,-2.2) {5};
  \draw[a] (r) -- (l); \draw[a] (r) -- (rr);
  \draw[a] (l) -- (ll); \draw[a] (l) -- (lr);
  \node[font=\small\bfseries, text=black!70] at (-3.6,-1.1) {pre: 1 2 4 5 3};
  \node[font=\small\bfseries, text=black!70] at (-3.6,-1.7) {in:  4 2 5 1 3};
  \node[font=\small\bfseries, text=black!70] at (2.2,-1.1) {post: 4 5 2 3 1};
  \node[font=\small\bfseries, text=black!70] at (2.2,-1.7) {level: 1 2 3 4 5};
\end{tikzpicture}

The names are worth memorizing with a mnemonic: pre = node first, in = node in the middle, post = node last. All three are depth-first; the only difference is the position of out.append(node.val).

Level-order traversal (BFS)

Level-order visits nodes by depth, left to right, using a queue (Chapter 5):

from collections import deque
def level_order(root):
    if not root:
        return []
    out, q = [], deque([root])
    while q:
        node = q.popleft()
        out.append(node.val)
        if node.left:  q.append(node.left)
        if node.right: q.append(node.right)
    return out

To print levels separately, record the queue length at the start of each level:

def levels(root):
    if not root: return []
    out, q = [], deque([root])
    while q:
        level = []
        for _ in range(len(q)):      # exactly this level's nodes
            node = q.popleft()
            level.append(node.val)
            if node.left:  q.append(node.left)
            if node.right: q.append(node.right)
        out.append(level)
    return out

Level-order is the backbone of “right side view”, “zigzag traversal”, “minimum depth”, and “connect nodes at the same level”.

Iterative traversals

Recursion uses the call stack; an iterative version uses an explicit stack. The iterative inorder is the one worth knowing cold:

def inorder_iter(root):
    out, stack, curr = [], [], root
    while curr or stack:
        while curr:                  # go as far left as possible
            stack.append(curr)
            curr = curr.left
        curr = stack.pop()           # visit
        out.append(curr.val)
        curr = curr.right            # then its right subtree
    return out

An iterative preorder is simpler: push the root, then pop and push right before left so the left child is processed first.

def preorder_iter(root):
    if not root: return []
    out, stack = [], [root]
    while stack:
        node = stack.pop()
        out.append(node.val)
        if node.right: stack.append(node.right)   # right pushed first
        if node.left:  stack.append(node.left)     # left popped first
    return out

Classic problems built on traversal

Height / max depth. The tree height is one plus the taller subtree:

def height(node):
    if not node:
        return 0
    return 1 + max(height(node.left), height(node.right))

Count nodes and sum values follow the same shape — a postorder fold.

def count(node):
    return 0 if not node else 1 + count(node.left) + count(node.right)

Invert a tree swaps children at every node:

def invert(node):
    if not node: return None
    node.left, node.right = invert(node.right), invert(node.left)
    return node

Diameter (longest path between any two nodes) needs two pieces of information per node: its height, and the best diameter seen so far.

def diameter(root):
    best = 0
    def h(node):
        nonlocal best
        if not node: return 0
        l, r = h(node.left), h(node.right)
        best = max(best, l + r)       # path through this node
        return 1 + max(l, r)
    h(root)
    return best

Notice the pattern: many tree problems are “compute something bottom-up at each node, and combine the children’s results”. That is divide-and-conquer over a tree (Chapter 24).

Pitfalls

QQuestionSelf-check

What single line distinguishes preorder, inorder, and postorder? When do you need an explicit stack or queue?

ASolution

The position of the visit (out.append(node.val)) relative to the two recursive calls: before both is preorder, between is inorder, after both is postorder. Use an explicit stack to avoid deep recursion on skewed trees, and a queue for level-order (BFS) traversal.

Next: Binary Search Trees (DSA #10) — trees that keep themselves searchable.