← Practice
📖 Trees and binary search treestree-max-depth
Lesson·difficulty 2/5·~12 min

Trees: maximum depth

Trees: maximum depth

A binary tree is a node with up to two children, left and right. The depth (or height) is the number of nodes on the longest path from the root down to a leaf. An empty tree has depth 0; a lone root has depth 1.

Trees love recursion: the depth of a node is 1 + the deeper of its two children. Hit a None? That's the base case — depth 0.

Here's build_bst([5, 3, 8, 2, 4]) — the longest root-to-leaf path is 3 nodes:

text
        5          depth 1:  5
       / \
      3   8        depth 2:  3, 8
     / \
    2   4          depth 3:  2, 4   ← longest path: 5 → 3 → 2

So the depth here is 3. Each node only has to ask its two children "how deep are you?" and add one. The trees here are binary search trees: build_bst(values) inserts each int in order, sending values < node left and >= right.

Your task

Write max_depth(root) returning the depth of the tree rooted at root (empty = 0, root-only = 1).

python
max_depth(build_bst([5, 3, 8, 2, 4]))   # 3
max_depth(build_bst([5]))               # 1
max_depth(build_bst([]))                # 0

Hint: if root is None return 0; otherwise return 1 + max(...) of the two recursive calls.

Tests

  • balanced-ish
  • single node
  • empty tree
  • right skewed (hidden)
  • left skewed (hidden)

✦ Stuck? Ask for a spark

warming up
Loading editor…

$ Console output will appear here.

>_AI tutor
Sign in to chat with the tutor.