Problem overview
maxDepth receives the root of a binary tree and returns its maximum depth: the number of nodes along the longest path from the root down to the farthest leaf. An empty tree, whose root is null, has depth 0.
The lesson provides the node class. A TreeNode is created with a value, TreeNode(3), and has two fields, left and right, which hold the child nodes or null when a child is missing.
For the tree with root 3, left child 9, and right child 20 whose children are 15 and 7, the answer is 3. The paths 3, 20, 15 and 3, 20, 7 each have three nodes, while 3, 9 has only two. A tree holding just the root 1 with a right child 2 has depth 2, and an empty tree has depth 0. The follow-up asks for O(n) time, visiting each node once.
Approach: one node deeper than the deeper subtree
A tree is built from smaller trees. The longest path from the root goes down through either the left child's subtree or the right child's subtree, and it takes whichever is deeper. So the depth of a tree is 1, for the root itself, plus the larger of the depths of its two subtrees.
That sentence is already a recursive definition, and it only needs a base case. A missing child is an empty tree, and an empty tree has depth 0. This one rule also ends the recursion: every path of calls eventually steps past a leaf and reaches null.
For the tree with root 3, the call on node 9 returns 1 plus the larger of 0 and 0. The call on node 20 returns 1 plus the larger of 1 and 1, which is 2. The root then returns 1 plus the larger of 1 and 2, which is 3.
Step by step
- Handle the empty tree. If
root == null, return 0. This is the base case, and it also covers every missing child below a leaf. - Find the left depth. Call
maxDepthonroot.leftand keep the result in avalnamedleftDepth. Trust the call to return the depth of the smaller tree, however it is shaped. - Find the right depth the same way with
root.right, stored inrightDepth. A missing child gives 0 here, thanks to the base case. - Combine them. Return 1 plus
math.max(leftDepth, rightDepth): the root, plus the longest path below it.
The solution in Scala
class Solution {
def maxDepth(root: TreeNode): Int = {
if (root == null) {
return 0
}
val leftDepth = maxDepth(root.left)
val rightDepth = maxDepth(root.right)
return 1 + math.max(leftDepth, rightDepth)
}
}
The Scala details worth a closer look:
- Recursive methods need a result type. Scala can infer many return types, but not for a method that calls itself. The
: Intin the signature is required. nulland==.root == nullis a safe test: in Scala==compares values, and it handlesnullon the left side without throwing an exception. The typeTreeNodeacceptsnullhere because the lesson's fields are initialised with it.return. The lesson usesreturnexplicitly. In Scala the last expression of a block is already its value, so1 + math.max(leftDepth, rightDepth)alone would do the same. The earlyreturn 0is the one place where it is useful.math.max. It takes two numbers of the same type and returns the larger. With twoInts it returns anInt.valfor results that don't change.leftDepthandrightDepthare assigned once, sovalis the right choice overvar.
Complexity
Time: O(n). The method is called once for every node, and once more for every missing child, which is at most n + 1 extra calls. Each call does a constant amount of work apart from its recursive calls.
Space: O(h), where h is the height of the tree. The recursion goes as deep as the tree does, and each active call holds a stack frame. For a balanced tree that is about log n. For a tree where every node has only a left child, it is n. The lesson promises at most 400 levels, which the JVM handles easily: a chain of 10,000 nodes also works.
Edge cases and common mistakes
- An empty tree.
maxDepth(null)returns 0. - A single node. Both children are
null, so the result is 1 plus the larger of 0 and 0, which is 1. - A lopsided tree. A root with a left leaf and a right child that has its own right child gives 3, because the deeper side wins.
- A line of nodes. A tree where each node has only a left child, 400 of them, returns 400. Taking the shorter side instead of the longer one with
math.minwould give 1 for a node with one missing child, which is wrong. - Forgetting the
1 +. Without it the method always returns 0. - Counting edges instead of nodes. The lesson counts nodes, so a single node has depth 1, not 0.
- Dropping the base case. Without the
nullcheck, the first call that reaches a missing child fails with aNullPointerExceptionwhen it readsroot.left.
Testing
- Root 3 with children 9 and 20, where 20 has children 15 and 7, gives
3. - Root 1 with only a right child 2 gives
2. - An empty tree gives
0. - A single node gives
1. - Root 1 with a left child 2 and a right child 3 that has a right child 4 gives
3. - A chain of 400 left children gives
400, and a chain of 10,000 gives10000.
