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, with a val and two children, left and right, each a TreeNode or null.
For the tree written in level order as [3,9,20,null,null,15,7], the node 3 has children 9 and 20, and 20 has children 15 and 7. The longest paths, 3 → 20 → 15 and 3 → 20 → 7, have 3 nodes, while 3 → 9 has only 2. The answer is 3.
Approach
A tree is built from smaller trees: each child of a node is the root of a subtree. That gives a way to state the answer in terms of itself:
depth(tree) = 1 + the larger of depth(left subtree) and depth(right subtree)
The 1 counts the root, and the larger depth is the longest path below it. An empty tree has depth 0, which ends the recursion. This is a depth-first walk: each node is visited once, so the time is O(n) for n nodes.
Step by step
- Base case. If
rootisnull(the test!rootis true), return 0. This also stops the recursion when it steps past a leaf, because a leaf's missing children arenull. - Depth of the left subtree. Call
this.maxDepth(root.left)and store it inleftDepth. Trust the call to return the right depth for the smaller tree, however it is shaped. - Depth of the right subtree. Do the same with
root.right. A missing child gives 0 thanks to the base case. - Combine them. Return
1 + Math.max(leftDepth, rightDepth): the root, plus the longest path through its deeper side.
The solution in TypeScript
class Solution {
maxDepth(root: TreeNode | null): number {
if (!root) {
return 0;
}
let leftDepth = this.maxDepth(root.left);
let rightDepth = this.maxDepth(root.right);
return 1 + Math.max(leftDepth, rightDepth);
}
}
Details for TypeScript:
this.maxDepth. Inside a class, a method calls itself throughthis. WritingmaxDepth(...)alone would look for a separate function with that name.!root.nullis falsy, and an object is truthy, so!rootis true exactly for an empty tree. ATreeNodeis always an object, even when itsvalis 0.- The parameter type
TreeNode | nulltells the compiler that the tree may be empty. It is erased when the code is compiled to JavaScript, so nothing about it is checked while the program runs. Math.maxtakes any number of arguments and returns the largest.
Walking through an example
On [3,9,20,null,null,15,7], the calls go down the tree and answer on the way back. Each indented line is a call one level deeper:
node 3
node 9
null -> 0
null -> 0
node 9 -> 1 + max(0, 0) = 1
node 20
node 15
null -> 0
null -> 0
node 15 -> 1 + max(0, 0) = 1
node 7
null -> 0
null -> 0
node 7 -> 1 + max(0, 0) = 1
node 20 -> 1 + max(1, 1) = 2
node 3 -> 1 + max(1, 2) = 3
Complexity
Time: O(n). Each node is visited once and does a constant amount of work. Space: O(h), where h is the height of the tree, for the recursion's call stack: one call per level of the path being followed. For a balanced tree h is about log n; for a tree that is a single chain it is n. The lesson's trees are at most 400 levels deep, which a JavaScript call stack handles easily. A chain of 400 nodes returns 400. A much deeper chain, such as 10,000 nodes, is a different matter: it overflows Node's default call stack with a RangeError.
Edge cases and common mistakes
- Empty tree.
root = []arrives asnulland the answer is 0. - A single node. Both children are
null, so the answer is1 + max(0, 0) = 1. - A one-sided tree. For
[1,null,2]the left depth is 0 and the right depth is 1, so the answer is 2. TakingMath.mininstead ofMath.maxwould wrongly give 1. - Forgetting the
1 +. Without it the function always returns 0. - Counting edges instead of nodes. The depth here counts nodes, so a single node has depth 1, not 0.
Testing
| Tree (level order) | Result |
|---|---|
[3,9,20,null,null,15,7] | 3 |
[1,null,2] | 2 |
[] | 0 |
[5] | 1 |
[1,2,null,3] | 3 |
