Problem overview
The function max_depth receives the root of a binary tree, an Option<Box<TreeNode>>, and returns its maximum depth: the number of nodes on the longest path from the root down to the farthest leaf. An empty tree, where the root is None, has depth 0. The lesson provides TreeNode, whose left and right fields are each an Option<Box<TreeNode>>.
For the tree [3, 9, 20, None, None, 15, 7] (level order, with None for a missing child), the root 3 has a left child 9 and a right child 20, and 20 has the children 15 and 7. The longest paths, 3 → 20 → 15 and 3 → 20 → 7, have 3 nodes, so the answer is 3. The path 3 → 9 has only 2. For [1, None, 2] the answer is 2, and for the empty tree it is 0.
Approach: one more than the deeper child
A tree is built from smaller trees, which suggests recursion. The depth of a tree is one node, the root, plus the longest path below it. The longest path below the root goes through one of the two children, so:
depth(tree) = 1 + max(depth(left subtree), depth(right subtree))
The recursion needs a place to stop. An empty tree has no nodes, so its depth is 0. This case also covers a missing child: a leaf has two empty children, and each answers 0, so a leaf has depth 1 + max(0, 0) = 1.
Each node is visited once, so the time is O(n) for n nodes. The lesson's tree is at most 400 levels deep, so the recursion depth, and with it the stack, stays small.
Step by step
- Match on
root. The whole body is onematch, with no semicolon after its closing brace, so the value of thematchis the value of the function. Its arms handle the two shapes of anOption: no node, or a node. - The base case. The arm
None => 0returns 0 for an empty tree. It also stops the recursion when it steps past a leaf. - The node arm.
Some(node)binds the box asnode. Its body is a block, because it needs several lines. Inside it,node.leftandnode.rightare the children, each anOptionof its own. - The left depth.
Self::max_depth(node.left)is stored inleft_depth. Trust the recursive call: it returns the depth of whatever tree hangs from the left child. - The right depth. The same for
node.right. A missing child gives 0 thanks to the base case. - Combine. End the arm with
1 + left_depth.max(right_depth), with no semicolon: the node itself, plus the longest path below it.
The solution in Rust
impl Solution {
fn max_depth(root: Option<Box<TreeNode>>) -> i32 {
match root {
None => 0,
Some(node) => {
let left_depth = Self::max_depth(node.left);
let right_depth = Self::max_depth(node.right);
1 + left_depth.max(right_depth)
}
}
}
}
The Rust details worth a closer look:
matchis an expression. Each arm produces a value, and the value of the arm that runs becomes the value of the wholematch. Because thematchis the last thing in the function, it is the returned value, and noreturnis needed.- The compiler checks the cases. A
matchmust cover every possibility, and the two armsNoneandSome(node)cover everyOption. Leaving one out is a compile error, which removes the "forgot the empty tree" bug. - The tree is moved, not borrowed. The function takes
rootby value, andSelf::max_depth(node.left)moves the left subtree into the call. This is fine because the function needs nothing from that subtree afterwards. Sincenode.leftandnode.rightare separate fields, they can be moved out one after the other. The tree is consumed by the call, and the caller can't use it afterwards. - The
Box. A struct can't contain itself directly, because its size would be infinite. ABoxis a pointer to a node on the heap, which givesTreeNodea fixed size. Fields of a box are used as usual:node.leftworks on aBox<TreeNode>without any extra syntax. Self::max_depth. The function has noselfparameter, so the recursive call is written throughSelf::, which names the type theimplblock belongs to.maxon integers.left_depth.max(right_depth)returns the larger of two values of the same type.
Complexity
Time: O(n). Each node gets exactly one call, plus one call for each missing child, so there are at most 2n + 1 calls, each doing a constant amount of work.
Space: O(h), where h is the height of the tree, for the recursion stack. In a balanced tree this is about log n. In the worst case, a tree shaped like a line, it is n, and the lesson's limit of 400 levels keeps that safe.
Edge cases and common mistakes
- An empty tree.
Nonematches the first arm and returns 0. - A single node. The tree
[1]has depth 1: both children areNone, so1 + max(0, 0). - A line of nodes.
[1, None, 2]has depth 2, and[1, 2, None, 3, None, 4], where every node has only a left child, has depth 4. The longer side is simply the one that exists. - Counting edges instead of nodes. The depth here counts nodes, so a single node is 1, not 0. The base case returning 0 for
None, together with the1 +, gives that. - Forgetting the
1 +. The function would return 0 for every tree, because it would only ever take the maximum of zeros. - Adding the depths instead of taking the larger.
left_depth + right_depthmeasures the total, not the longest path. - A semicolon after the last expression.
1 + left_depth.max(right_depth);turns the arm's value into(), and the compiler reports a type mismatch.
Testing
[3, 9, 20, None, None, 15, 7]gives3.[1, None, 2]gives2.[]gives0.[1]gives1.[1, 2, None, 3, None, 4]gives4.
