Problem overview
The method maxDepth receives the root of a binary tree and returns its maximum depth: the number of nodes on the longest path from the root down to a leaf. An empty tree, where root is null, has depth 0.
The lesson provides the TreeNode class. It has an int val, a TreeNode left, a TreeNode right and a constructor TreeNode(int x); a missing child is null.
For the tree [3,9,20,null,null,15,7], the paths 3, 20, 15 and 3, 20, 7 have three nodes each, while 3, 9 has two. The answer is 3. For [1,null,2] the only path is 1, 2, so the answer is 2.
Approach: a tree is one deeper than its deeper subtree
Every tree is a root with a left subtree and a right subtree, and both are themselves binary trees, possibly empty. The longest path from the root must go down through one of the two children, so:
depth(tree) = 1 + max(depth(left subtree), depth(right subtree))
The 1 counts the root. For an empty tree the depth is 0, which is where the recursion stops. A leaf then works out by itself: both children are empty, so its depth is 1 + max(0, 0) = 1.
This visits every node exactly once, so the time is O(n) for n nodes. The statement's follow-up asks for exactly that.
Step by step
- Write the base case. If
root == null, return 0. This handles the empty tree and also ends the recursion when it steps below a leaf. - Find the left depth. Call
maxDepth(root.left)and store the result in anintnamedleftDepth. Trust the call to return the right answer for the smaller tree, whatever its shape. - Find the right depth the same way, from
root.right, intorightDepth. A missing child gives 0 thanks to the base case, so one-sided trees need no special handling. - Combine. Return
1 + Math.max(leftDepth, rightDepth): the root, plus the longest path below it.
The solution in Java
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return 1 + Math.max(leftDepth, rightDepth);
}
}
Java details worth knowing:
root == nullis a reference check. ATreeNodevariable holds either a reference to a node ornull. Readingroot.leftwhenrootisnullthrows aNullPointerException, which is why the base case comes first.- Each call has its own variables.
leftDepthandrightDepthare local to one call, so the recursive calls don't interfere with each other. - Recursion uses the call stack. The recursion goes as deep as the tree. With a tree at most 400 levels deep, as here, that is no problem. A tree that is a chain of a hundred thousand nodes could overflow the stack with this approach, and an iterative level-by-level search would be needed.
Math.maxtakes twoints and returns the larger one.
Complexity
Time: O(n). Each node is visited once, and each visit does a constant amount of work. Each null child is also visited once and returns at once, which adds at most n + 1 extra calls.
Space: O(h), where h is the height of the tree, for the call stack. That is about log n for a balanced tree and n for a chain.
Edge cases and common mistakes
- Empty tree.
root = nullreturns 0. - Single node. A tree holding just 5 returns 1.
- A chain.
[1,null,2]returns 2, and[1,2,null,3]returns 3, because a missing child contributes 0. - Forgetting the
1 +. Without it, the method returns 0 for every tree. - Adding 1 only at leaves. Every node on the path counts, not just the last one, so the
1 +belongs in the general case, not only in a special case for leaves. - Counting edges instead of nodes. The lesson counts nodes, so a single node has depth 1, not 0.
Testing
These results come from running the solution on trees written in level order:
[3,9,20,null,null,15,7]gives 3.[1,null,2]gives 2.[]gives 0.[5]gives 1.[1,2,null,3]gives 3.
