Skip to content
Visual explainer 3h 30m to learn 5 steps

Binary trees & traversals

Traverse a binary tree in pre-, in-, post- and level order, recursively and iteratively.

By Invicly Tech, , in Data Structures & Algorithms. About 11 minutes to read.

Topic 25 of 54

In short

A binary tree is a hierarchy where each node has at most two children. Depth-first traversals visit nodes in pre-order, in-order or post-order, and breadth-first traversal visits level by level with a queue. Most tree problems are a traversal plus a little work at each node.

Explained simply

A tree is like a family tree or a folder structure on your computer. There is one top item, the root. Each item can have children below it. Items with no children are leaves. In a binary tree, every item (called a node) has at most two children: a left one and a right one.

Traversing a tree means visiting every node once. There are two big styles. Depth-first goes as deep as possible down one branch before coming back. Breadth-first visits the tree level by level, like reading a page line by line.

Depth-first has three flavours, depending on when you handle the node itself. Pre-order: the node first, then its children. In-order: left child, then the node, then right child. Post-order: both children first, then the node.

Which one you choose depends on the question. Copying a tree? Pre-order, because you need the parent before its children. Deleting a tree or adding up sizes? Post-order, because you need the children's answers first. Printing a search tree in sorted order? In-order.

Press Play on a diagram to walk through it one step at a time.

MapExample tree and traversal orders
1
  • 2
    • 4
    • 5
  • 3
  • Pre-order: 1 2 4 5 3
  • In-order: 4 2 5 1 3
  • Post-order: 4 5 2 3 1
CompareWhich traversal for which job
Pre-order
  • Node before children
  • Copy or serialise a tree
  • Print folder structure
  • Path from root to each node
In-order
  • Left, node, right
  • BST keys in sorted order
  • k-th smallest in a BST
  • Validate a BST
Post-order
  • Children before node
  • Height, size, sums
  • Delete or free a tree
  • Evaluate an expression tree

In depth

Tree vocabulary with exact numbers

The depth of a node is the number of edges from the root to it; the root has depth 0. The height of a tree is the largest depth of any node, so a single node has height 0 and an empty tree is often given height -1. Some books count nodes instead of edges, so always check which convention a problem uses.

A binary tree of height h holds at most 2^(h+1) - 1 nodes, when every level is full. So n nodes need height at least floor(log2 n). The other extreme is a chain where each node has one child: height n - 1.

A full binary tree has 0 or 2 children at every node. A complete binary tree fills every level except possibly the last, which fills from the left (this is the shape of a heap). A perfect tree has every level completely full. A tree with n nodes always has exactly n - 1 edges.

  • Depth counts down from the root; height is the maximum depth
  • Height h: at most 2^(h+1) - 1 nodes
  • n nodes: exactly n - 1 edges

Iterative traversals with an explicit stack

Recursive traversals use the call stack, which in Python fails on chains deeper than about 1000 nodes. An explicit stack has no such limit.

Pre-order is the easiest: push the root; pop a node, record it, push its right child and then its left child (so left is popped first).

In-order needs a pointer. Starting at the root, push nodes while going left. When you cannot go left, pop a node, record it, and move to its right child. Repeat while the pointer is not None or the stack is not empty.

Post-order can be done by reversing a modified pre-order: record node, then visit right before left, and reverse the result at the end. That gives left, right, node. It uses O(n) extra memory for the output, which you need anyway.

All of these take O(n) time and O(h) stack. Morris traversal achieves O(1) extra space for in-order by temporarily rewiring right pointers, then restoring them.

CycleIterative in-order loop
  1. 1
    Go left

    Push the current node, move to its left child.

  2. 2
    Hit None

    No more left children.

  3. 3
    Pop

    Record the popped node's value.

  4. 4
    Go right

    Move to the popped node's right child.

  5. Back to step 1

Level order and per-level answers

Breadth-first traversal uses a queue (collections.deque, whose popleft is O(1)). Put the root in. Repeatedly take the front node, record it and add its children to the back.

Many questions need the levels separated: the right side view, the average per level, or zigzag order. The trick is to read len(queue) at the start of each round. That many nodes belong to the current level; process exactly that many, and everything added meanwhile belongs to the next level.

BFS memory is O(w), where w is the maximum width. For a perfect tree, the last level holds about half the nodes, so BFS can need O(n) memory while DFS needs only O(log n). For a chain it is the reverse. BFS also finds the shallowest node that satisfies a condition first, such as the minimum depth to a leaf, and can stop early.

  • for _ in range(len(q)) processes exactly one level
  • BFS memory O(width), DFS memory O(height)
  • Minimum depth: BFS stops at the first leaf

Post-order thinking: height and diameter

Many tree problems follow one pattern: ask each child for an answer, combine those answers at the node, and return the result upward. That is a post-order traversal.

Height: h(node) = 1 + max(h(left), h(right)), with h(None) = -1 when counting edges.

Diameter is the longest path between any two nodes, measured in edges. It may not pass through the root. At each node, the longest path that bends there goes down the left side and down the right side: (h(left) + 1) + (h(right) + 1). Keep the best such value in a variable while computing heights, and you get the diameter in one O(n) pass. Computing height separately at every node would be O(n^2) for a chain.

The same pattern solves balanced-tree checks, maximum path sum, subtree sums and lowest common ancestor. Return what the parent needs, and update a global answer for what the whole tree needs.

FlowDiameter in one pass
  1. 1
    Recurse left

    Get left height L.

  2. 2
    Recurse right

    Get right height R.

  3. 3
    Path through node

    (L + 1) + (R + 1) edges.

  4. 4
    Update best

    best = max(best, path).

  5. 5
    Return

    1 + max(L, R) to the parent.

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Learn tree vocabulary: root, leaf, height~40m
  2. 2
    Implement pre-, in- and post-order~40m
  3. 3
    Implement level-order with a queue~40m
  4. 4
    Write iterative traversals with a stack~40m
  5. 5
    Compute height and diameter~40m

Key points

  • Every traversal is O(n) time.
  • Space is O(h) for DFS, where h is height, and O(width) for BFS.
  • Post-order fits problems where a node needs its children's answers first.
  • Height and diameter are computed in one post-order pass.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
from collections import deque

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

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

def levels(root):
    out, q = [], deque([root] if root else [])
    while q:
        out.append([n.val for n in q])
        q = deque(c for n in q for c in (n.left, n.right) if c)
    return out

Iterative in-order on a deep tree

We build a chain of 5,000 nodes, each the left child of the next, so the tree has height 4,999. A recursive in-order would raise RecursionError at the default limit of 1000. The stack-based version walks down the left spine, pushing every node, then pops them in increasing order. It visits all 5,000 values in O(n) time.

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

def inorder_iter(root):
    out, stack, node = [], [], root
    while node or stack:
        while node:
            stack.append(node); node = node.left
        node = stack.pop()
        out.append(node.val)
        node = node.right
    return out

root = None
for v in range(5000): root = TreeNode(v, left=root)
print(inorder_iter(root)[:3], len(inorder_iter(root)))  # [0, 1, 2] 5000

Diameter and right side view

Take the tree 1 with children 2 and 3, where 2 has children 4 and 5. The diameter is 3 edges (4 to 2 to 1 to 3, or 5 to 2 to 1 to 3). The right side view lists the last node of each level: [1, 3, 5]. Both use the reusable patterns: post-order with a running best, and BFS level by level.

python
from collections import deque

def diameter(root):
    best = 0
    def h(n):
        nonlocal best
        if not n: return -1
        L, R = h(n.left), h(n.right)
        best = max(best, L + R + 2)
        return 1 + max(L, R)
    h(root); return best

def right_view(root):
    out, q = [], deque([root] if root else [])
    while q:
        out.append(q[-1].val)
        for _ in range(len(q)):
            n = q.popleft(); q.extend(c for c in (n.left, n.right) if c)
    return out

Quick reference

  • Pre: node, left, right. In: left, node, right. Post: left, right, node
  • All traversals: O(n) time; DFS O(h) space, BFS O(max width) space
  • Height h binary tree: at most 2^(h+1) - 1 nodes; n nodes have n - 1 edges
  • BFS levels: for _ in range(len(q)) inside while q
  • Iterative pre-order: pop, record, push right then left
  • Diameter = max over nodes of (left height + 1) + (right height + 1)
  • Preorder plus inorder (distinct values) uniquely rebuild a binary tree

Common mistakes

  • Recursing on very deep, skewed trees and hitting the recursion limit.
  • Confusing height in nodes with height in edges.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A binary tree has height 3 (counted in edges). What is the maximum number of nodes?

Question 2

2Which traversal should you use to compute the size of every subtree?

Question 3

3In iterative pre-order, why push the right child before the left child?

Question 4

4For a perfect binary tree of n nodes, which uses more memory?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write max_depth(root) that returns the number of nodes on the longest root-to-leaf path (0 for an empty tree), recursively. Example: the tree 1 -> (2 -> (4, 5), 3) has max depth 3.

  2. Exercise 2medium

    Write zigzag(root) that returns level order values with direction alternating each level: left to right, then right to left. Example: tree 1 -> (2 -> (4, 5), 3) gives [[1], [3, 2], [4, 5]].

  3. Exercise 3hard

    Write build(preorder, inorder) that rebuilds a binary tree with distinct values in O(n). Example: preorder [3, 9, 20, 15, 7], inorder [9, 3, 15, 20, 7] gives root 3, left 9, right 20 with children 15 and 7.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is height counted in nodes or edges?
Both conventions exist. Most textbooks count edges (a single node has height 0), while many coding problems such as maximum depth count nodes. Read the problem's examples to check.
When should I use BFS instead of DFS on a tree?
Use BFS when you need levels or the shallowest match, such as minimum depth. Use DFS for most other problems, because it is shorter to write and uses O(h) memory.
Can one traversal order rebuild a tree?
Not in general. With distinct values, preorder plus inorder (or postorder plus inorder) is enough. A serialisation that records None children, like preorder with null markers, works with a single list.

Go deeper

ShareXLinkedInWhatsApp