Maximum Depth of Binary Tree - Problem

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Think of it as measuring how "tall" your tree is - counting every level from top to bottom.

Example: If you have a tree that goes Root โ†’ Child โ†’ Grandchild, that's a depth of 3 nodes.

Note: An empty tree has a depth of 0, and a single node has a depth of 1.

Input & Output

example_1.py โ€” Standard Binary Tree
$ Input: root = [3,9,20,null,null,15,7]
โ€บ Output: 3
๐Ÿ’ก Note: The tree has 3 levels: root(3) โ†’ level 2(9,20) โ†’ level 3(15,7). The maximum depth is 3.
example_2.py โ€” Single Path Tree
$ Input: root = [1,null,2]
โ€บ Output: 2
๐Ÿ’ก Note: The tree has only a right path: 1 โ†’ 2. The maximum depth is 2 nodes along this path.
example_3.py โ€” Single Node
$ Input: root = [5]
โ€บ Output: 1
๐Ÿ’ก Note: A tree with just one node (the root) has a depth of 1.

Visualization

Tap to expand
Tree Depth Calculation - Family Tree AnalogyGreatGrandparentDepth: 3GrandparentDepth: 1GrandparentDepth: 2ParentDepth: 1ParentDepth: 1Recursive Depth Calculation:โ€ข Bottom Generation (Parents): max(0, 0) + 1 = 1โ€ข Middle Left (Grandparent): max(0, 0) + 1 = 1โ€ข Middle Right (Grandparent): max(1, 1) + 1 = 2โ€ข Top (Great-Grandparent): max(1, 2) + 1 = 3๐ŸŽฏ Total Family Tree Depth: 3 Generations
Understanding the Visualization
1
Start at leaf level
Childless nodes (leaves) represent generation 1 - they have depth 1
2
Build upward
Each parent's generation depth = 1 + max(children's depths)
3
Propagate to root
This calculation bubbles up to the root, giving total tree depth
4
Handle edge cases
Empty tree has depth 0, single node has depth 1
Key Takeaway
๐ŸŽฏ Key Insight: Each node only needs to know its children's maximum depth and add 1 - the recursive structure naturally solves the problem!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

We visit each node exactly once in the tree

n
2n
โœ“ Linear Growth
Space Complexity
O(h)

Recursion stack depth equals tree height h. O(log n) for balanced tree, O(n) for skewed tree

n
2n
โœ“ Linear Space

Constraints

  • The number of nodes in the tree is in the range [0, 104]
  • -100 โ‰ค Node.val โ‰ค 100
  • Tree depth will not exceed typical recursion stack limits
Asked in
Google 65 Amazon 58 Microsoft 42 Meta 38
89.4K Views
Very High Frequency
~8 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen