Skip to the content.

7. Binary Trees and Traversals

Back to the index

Each node has up to two children. The four traversals (preorder, inorder, postorder, level order) are the building blocks of almost every tree problem.

How it works

A binary tree is either empty or a node with a left subtree and a right subtree. Depth-first traversals differ only in when the node itself is visited relative to its subtrees:

The trace below shows iterative inorder with an explicit stack, which is what recursion does behind the scenes.

Diagram

graph TD
    n_1["1"]
    n_1 -->|L| n_2
    n_1 -->|R| n_3
    n_3["3"]
    n_3 -->|R| n_6
    n_6["6"]
    n_2["2"]
    n_2 -->|L| n_4
    n_2 -->|R| n_5
    n_5["5"]
    n_4["4"]

Step-by-step trace

Input: Tree built from level-order list [1, 2, 3, 4, 5, None, 6]. Iterative inorder traversal.

Step Action Stack (bottom -> top) Output so far
1 push 1, go left [1] []
2 push 2, go left [1, 2] []
3 push 4, go left [1, 2, 4] []
4 pop and visit 4, no right child [1, 2] [4]
5 pop and visit 2, go right to 5 [1] [4, 2]
6 push 5, go left [1, 5] [4, 2]
7 pop and visit 5, no right child [1] [4, 2, 5]
8 pop and visit 1, go right to 3 [] [4, 2, 5, 1]
9 push 3, go left [3] [4, 2, 5, 1]
10 pop and visit 3, go right to 6 [] [4, 2, 5, 1, 3]
11 push 6, go left [6] [4, 2, 5, 1, 3]
12 pop and visit 6, no right child [] [4, 2, 5, 1, 3, 6]

Result: Inorder result: [4, 2, 5, 1, 3, 6].

Input: All four traversals of the same tree.

Traversal Order
Preorder (node, left, right) [1, 2, 4, 5, 3, 6]
Inorder (left, node, right) [4, 2, 5, 1, 3, 6]
Postorder (left, right, node) [4, 5, 2, 6, 3, 1]
Level order (BFS) [1, 2, 3, 4, 5, 6]

Complexity

Operation Time Space
Any traversal O(n) O(h) stack, O(w) queue for BFS
Height h of a balanced tree - O(log n)
Height h of a degenerate (list-like) tree - O(n)

Python reference implementation

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


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


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


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


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


def inorder_iterative(root):
    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()       # visit
        out.append(node.val)
        node = node.right        # then handle the right subtree
    return out

Common mistakes and tips


The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.

Previous: LRU Cache (Hash Map + Doubly Linked List) Next: Binary Search Trees