Binary Trees/Practice/Maximum Depth of Binary Tree
Maximum Depth of a Binary Tree - Explained Visually
easyTime: O(n)Space: O(h)
Ask each node a simple question: how deep are my left and right subtrees? The answer is one plus the deeper of the two. Leaves answer 1, and the answers bubble up to the root.
Why it works
The recursion touches every node exactly once and does constant work per node, so it is O(n) time. Space is the call stack at its deepest - O(h) where h is tree height, O(log n) for balanced trees and O(n) for a degenerate chain.
The problem
Given the root of a binary tree, return its maximum depth. The maximum depth is the number of nodes along the longest path from the root down to the farthest leaf.
Hints
- Think recursively: the depth of a tree is 1 + max depth of its subtrees.
- Base case: if root is None, return 0.
- Alternatively, use BFS and count levels.
Test cases
| Input | Expected |
|---|---|
max_depth([3,9,20,null,null,15,7]) | 3 |
max_depth([1,null,2]) | 2 |
max_depth(None) | 0 |
Reference starter code
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def max_depth(root):
# Recursive or iterative
pass
# Build tree [3,9,20,None,None,15,7]
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
print(max_depth(root)) # 3
print(max_depth(None)) # 0
More challenges in this topic
Try it yourself
Solve it in the browser editor with real test cases and instant feedback - free, no signup needed.
Next challenge in this topic: Validate Binary Search TreeStudying Binary Trees but not ready to grind? Get the 30-day plan by email.
One email with the study plan. No spam, unsubscribe anytime.