Problem overview
maxDepth receives the root of a binary tree, a TreeNode?, 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 node class: a TreeNode has an Int field value and two nullable children, left and right.
For the tree [3,9,20,null,null,15,7] the root 3 has a left child 9 and a right child 20, and 20 has children 15 and 7. The longest paths, 3 -> 20 -> 15 and 3 -> 20 -> 7, have 3 nodes, so the answer is 3. For [1,null,2] it is 2, and for the empty tree it is 0.
Approach
A tree is one node deeper than the deeper of its two subtrees. The root adds one level, and below it the longest path goes through the left or the right child, whichever is deeper. A subtree is itself a binary tree, so the same function can compute its depth. That is recursion.
A recursive function needs a base case that stops it. Here it is the empty tree, null, whose depth is 0. A leaf has two null children, so it gets 1 + max(0, 0) = 1.
Each node is visited once, so the time is O(n) for n nodes.
Step by step
- Handle the empty tree. If
root == null, return 0. This check also stops the recursion when it steps past a leaf. - Find the left depth. Call
maxDepth(root.left)and keep the result inleftDepth. Trust the call to return the depth of the left subtree, whatever its shape. - Find the right depth the same way, with
root.right. A missing child gives 0 thanks to the base case. - Combine. Return
1 + maxOf(leftDepth, rightDepth): the root itself plus the longest path below it.
The solution in Kotlin
class Solution {
fun maxDepth(root: TreeNode?): Int {
if (root == null) {
return 0
}
val leftDepth = maxDepth(root.left)
val rightDepth = maxDepth(root.right)
return 1 + maxOf(leftDepth, rightDepth)
}
}
Some Kotlin details in this code:
- The parameter type
TreeNode?allowsnull. After theif (root == null)check that returns, Kotlin knowsrootis notnull(a smart cast), soroot.leftis written without?.. root.leftandroot.rightare themselves nullable, which is whymaxDepthtakes aTreeNode?: the recursive calls can pass them directly.maxOf(leftDepth, rightDepth)returns the larger of twoIntvalues.- A method can call itself by name, here
maxDepth, as long as its return type is declared, which it is.
Tracing the first example
Running the function on the example tree and on some of its subtrees gives:
tree rooted at 3: 3
subtree rooted at 9: 1
subtree rooted at 20: 2
The node 9 is a leaf, so its depth is 1. The node 20 has two leaf children, so its depth is 1 + max(1, 1) = 2. The root takes the larger of 1 and 2 and adds 1, which is 3.
Complexity
Time: O(n). Every node is visited exactly once, and each visit does constant work.
Space: O(h), where h is the height of the tree. The recursion keeps one call open per level of the current path. For a balanced tree that is about log n, and for a tree that is a single chain it is n. The lesson's trees are at most 400 levels deep, which is a safe depth for recursion.
Edge cases and common mistakes
- Empty tree.
nullgives 0. - Single node. A tree with only a root gives 1.
- A chain.
[1,null,2]gives 2. A chain of 400 nodes, each the left child of the next, gives 400. - Returning the wrong base value. Depth counts nodes, not edges, so an empty tree is 0 and a leaf is 1. Returning 1 for
nullwould make every answer too large by one. - Forgetting the
1 +. Without it the function returns 0 for every tree. - Using
+instead ofmaxOf. Adding the two depths counts the nodes of both sides rather than the longest path.
Testing
[3,9,20,null,null,15,7] -> 3
[1,null,2] -> 2
[] -> 0
[7] -> 1
