The problem, in one line. Given a binary tree, return how many nodes lie on the longest path from the root down to a leaf. LeetCode 104.
The tell. A question about the whole tree that can be answered by asking the same question of the left and right child. “Longest” plus “tree” means ask both sides and keep the bigger answer.
The wrong first idea
Follow the left child all the way down and count the steps.
d = 0
while root:
d += 1
root = root.left
That is fast and often right, which is the danger. On [1, None, 2, None, 3] every node hangs on the right, so it answers 1 when the depth is 3. Patching it to “go left, else right” still misses any tree that forks.
The invariant
The clinic Clinic #09: Maximum Depth of Binary Tree walks this one slowly, and this card is its short form. Read the answer up from the leaves:
depth(15) = 1 depth(7) = 1 depth(9) = 1
depth(20) = 1 + max(1, 1) = 2
depth(3) = 1 + max(1, 2) = 3
The sentence that stays true: the depth of a node is 1 plus the deeper of its two children, and an empty spot is 0.
The solution
The helper build turns a level-order list into nodes, with None for a gap.
class Node:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def build(xs):
ns = [None if x is None else Node(x) for x in xs]
kids = iter(ns[1:])
for n in ns:
if n: n.left, n.right = next(kids, None), next(kids, None)
return ns[0] if ns else None
def max_depth(root):
if not root: return 0
return 1 + max(max_depth(root.left), max_depth(root.right)) # me plus the deeper child
print(max_depth(build([3, 9, 20, None, None, 15, 7])))
print(max_depth(build([1, None, 2])))
print(max_depth(build([])))
3
2
0
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
return 1 + max(maxDepth(root.Left), maxDepth(root.Right)) // me plus the deeper child
}
Go uses a TreeNode with Val, Left and Right, and the same calls print 3, 2, 0.
Complexity
- Time O(n): every node is asked once.
- Space O(h): one stack frame per level, so n for a chain.
Traps
- Counting a leaf as 0. The tree
[1]has one node on its path, so the answer is 1, and a base case of “leaf returns 0” gives 0. - Deep trees in Python. A chain of 5,000 nodes raises
RecursionErrorat the default limit of 1,000, so a long chain needs a loop with a queue or a higher limit. - Looking at one side only. The left-only walk answers 1 for
[1, None, 2, None, 3].
Next in the ladder
Diameter of Binary Tree uses this same depth function, and also records something at every node, because the best answer may bend below the root.