Trees, DFS & BFS

Data Structures & Algorithms · Trees & Heaps · Intermediate · 16 min

Hierarchies like family trees and folders, and two ways to explore them.

A family tree drawn on a wall. DFS is a child running down one branch to the very bottom before coming back up to try the next branch. BFS is a photographer taking one photo per generation, from the oldest down.

The idea in everyday words

A tree is your computer's folders: one root folder, each folder has sub-folders. DFS = open the first folder, then its first sub-folder, going as deep as possible before backing up. BFS = look at everything on floor 1, then floor 2, like an elevator stopping at each level.

Words to know

  • Root: top node. Leaf: node with no children.
  • Binary tree: each node has at most 2 children (left, right).
  • BST: left < node < right → search in O(log n) when balanced.
  • Depth of a node: how many steps down from the root it is (the root has depth 0).
  • Height of a node: how many steps (edges) from it down to its deepest leaf, so a leaf has height 0. Some lessons and books count LEVELS instead, so a leaf has height 1. The two answers always differ by exactly 1. The Code along tab counts levels (a leaf is 1, an empty tree is 0), the same way as max depth below.
  • Max depth of a tree (this lesson's challenge): the number of LEVELS, so a single node counts 1 and an empty tree 0. Some books count edges instead of levels, so always say which one you mean.

DFS (recursion) vs BFS (queue)

DFS: visit(node) → visit(left) → visit(right). Great for depth, paths, validating BSTs. BFS: put root in a queue; pop, then push its children. Great for 'level order' and shortest path in unweighted graphs.

Max depth with DFS: depth(node) = 1 + max(depth(left), depth(right)), and depth(None) = 0.

Preorder, inorder, postorder: same walk, different moment

All three DFS orders walk the tree in exactly the same way. The only difference is when you write the node down:

Order Visit the node... Typical use
Preorder before its children copy a tree, print a folder structure
Inorder between left and right a BST comes out sorted
Postorder after both children sizes, heights, deleting a tree
tree = [4, [2, [1, None, None], [3, None, None]], [6, [5, None, None], [7, None, None]]]

def walk(t, pre, ino, post):
    if t is None:
        return
    v, left, right = t
    pre.append(v)
    walk(left, pre, ino, post)
    ino.append(v)
    walk(right, pre, ino, post)
    post.append(v)

pre, ino, post = [], [], []
walk(tree, pre, ino, post)
print("pre: ", pre)
print("in:  ", ino)
print("post:", post)

Max depth is a postorder problem: you can only know a node's depth after both children have answered.

Step by step

  1. Tree:
    1
    

    /
    2 3 / 4

  2. depth(4):

    Leaf: 1 + max(0, 0) = 1

  3. depth(2):

    1 + max(depth(4)=1, 0) = 2

  4. depth(3):

    Leaf → 1

  5. depth(1):

    1 + max(2, 1) = 3 ✅

Code example

from collections import deque

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

def max_depth(node):
    if node is None:
        return 0
    return 1 + max(max_depth(node.left), max_depth(node.right))

def level_order(root):
    if root is None:
        return []
    q, out = 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

root = TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3))
print("depth:", max_depth(root))
print("BFS:", level_order(root))

Complexity

  • Time: O(n) – visit each node once
  • Space: O(h) DFS stack / O(w) BFS queue

Interview tips

  • Max depth, invert tree, same tree, level order: the four warm-ups.

  • Validate BST: pass allowed (min, max) range down the recursion.

  • Lowest common ancestor is a favourite at big tech.

Challenge: Max Depth of a Nested Tree

A tree is given as nested lists: [value, left, right] where left/right are another tree or None/null.

Return its maximum depth.

Example: [1, [2, [4, None, None], None], [3, None, None]] → 3

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Trees & Heaps

Previous: Inside a Hash Table · Next: Binary Search Trees