Neural Mastery
← Practice
Maximum Depth of Binary Treeeasy

Maximum Depth of Binary Tree

easy Coding Interview Patterns 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Interactive
Graph & Tree Traversal, Step by Step
Structure
Algorithm
ABCDE
visiting A -> visited order so far: [A]
queue now: [B, C]
Step 1 / 5
Both modes run the real algorithm from the linked practice problem, one step at a time -- edit the graph or pick different tree nodes and every step recomputes live.

Implement Maximum Depth of Binary Tree -- the simplest possible tree recursion, and the one every other "compute something about every subtree" tree problem is a variation of.

Related Skills

Task

Implement max_depth(root): an empty tree has depth 0; otherwise the depth is 1 plus the larger of the left and right subtrees' depths.

Function Signature

max_depth(root: dict | None) -> int

Examples

Example 1: Classic 5-Node Tree
Input: root = {'val': 3, 'left': {'val': 9, 'left': None, 'right': None}, 'right': {'val': 20, 'left': {'val': 15, 'left': None, 'right': None}, 'right': {'val': 7, 'left': None, 'right': None}}}
Output: 3
Example 2: Right-Leaning 2-Node Tree
Input: root = {'val': 1, 'left': None, 'right': {'val': 2, 'left': None, 'right': None}}
Output: 2

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • An empty tree (root is None) has depth 0.
  • A single-node tree has depth 1.
Python3Saved ✓
def max_depth(root: dict | None) -> int:
"""root: a tree node as {'val', 'left', 'right'} (left/right are None
for an absent child), or None for an empty tree. Return the number
of nodes along the longest path from root down to the farthest leaf
(an empty tree has depth 0; a single node has depth 1)."""
# Your implementation here
pass

Case 1: Classic 5-Node Tree
Input: root = {'val': 3, 'left': {'val': 9, 'left': None, 'right': None}, 'right': {'val': 20, 'left': {'val': 15, 'left': None, 'right': None}, 'right': {'val': 7, 'left': None, 'right': None}}}
Expected: 3
Case 2: Right-Leaning 2-Node Tree
Input: root = {'val': 1, 'left': None, 'right': {'val': 2, 'left': None, 'right': None}}
Expected: 2