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. A node has an int val and two TreeNode fields, left and right, which are null when the child is missing. A TreeNode is created with new TreeNode(x).
For the tree [3,9,20,null,null,15,7], listed level by level, the root 3 has children 9 and 20, and 20 has children 15 and 7. The paths 3, 20, 15 and 3, 20, 7 have three nodes, and 3, 9 has two, so the answer is 3. For [1,null,2] the answer is 2, and for an empty tree it is 0. Counting nodes rather than edges is the point to remember: a single node has depth 1.
Approach: one more than the deeper subtree
A tree is built from smaller trees, and its depth follows the same pattern. The longest path from the root goes down through either the left child or the right child, so the depth of a tree is one (for the root) plus the larger of the depths of its two subtrees.
That sentence is already a recursive algorithm. To find the depth of a tree, find the depth of the left subtree, find the depth of the right subtree, and combine them. You don't need to follow what happens inside the recursive calls: trust that each call returns the right depth for the smaller tree it receives.
The recursion needs a base case, and the natural one is the empty tree: its depth is 0. This single check also handles every missing child. A leaf has two null children, so both recursive calls return 0, and the leaf's own depth is 1 + max(0, 0), which is 1.
Each node is visited exactly once, so the method runs in O(n) time for a tree of n nodes. Depth could also be found level by level with a queue, but the recursive version is shorter.
Running the method on a few trees gives these depths: [3,9,20,null,null,15,7] gives 3, [1,null,2] gives 2, an empty tree gives 0, a single node [5] gives 1, and a chain of four nodes that keeps going left, [1,2,null,3,null,4], gives 4.
Step by step
- Write the base case. If
root == null, return 0. An empty tree has no nodes. This check also stops the recursion when it steps past a leaf. - Find the left depth. Call
MaxDepth(root.left)and store the result in anintnamedleftDepth. The call returns the depth of whatever tree hangs under the left child. - Find the right depth the same way with
root.right, and store it inrightDepth. A missing child simply gives 0, thanks to the base case. - Combine them. Return
1 + Math.Max(leftDepth, rightDepth): the root itself plus the longest path below it.
The solution in C#
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);
}
}
The C# details worth knowing:
- Class instances are references.
TreeNodeis a class, so aTreeNodevariable holds a reference that can benull. That is whyroot == nullis a valid test, and why a missing child is just anullfield. - Field names are lowercase here. The lesson's
TreeNodeusesval,leftandright, while the method isMaxDepth. Method names in C# are PascalCase by convention, but the tree's fields follow the names the lesson provides. Use them exactly:root.Leftwould not compile. Math.Maxis inSystem. It takes two numbers of the same type and returns the larger one.- A method can call itself. No special syntax is needed. Each call gets its own
root,leftDepthandrightDepth. - Recursion depth is the tree's height. The lesson's trees are at most 400 levels deep, which is far below the limit of the call stack. A degenerate chain of 10,000 nodes, all left children, also returns 10000 without trouble, but a much longer chain could overflow the stack, which ends the program.
Complexity
Time: O(n). Every node causes one call that does constant work, plus one call for each missing child that returns at once. That is at most about 2n + 1 calls.
Space: O(h), where h is the height of the tree, for the call stack. For a balanced tree that is about log n. For a chain where every node has one child, it is n. The method allocates nothing else.
Edge cases and common mistakes
- Empty tree.
nullreturns 0. - A single node. It returns 1: both children are missing, so the answer is
1 + Math.Max(0, 0). - A chain. A tree where each node has only a right child, such as
[1,null,2], returns its length, 2. A missing left child doesn't make the tree shallower. - Counting edges instead of nodes. The depth here is the number of nodes on the path. Returning 0 for the base case and 0 for a leaf would give one less than the expected answer.
- Using
+instead ofMath.Max. Adding the two depths counts both subtrees, which isn't a path from the root to a leaf. - Forgetting the base case. Without it the recursion would call
MaxDepthonnulland then readnull.left, which throwsNullReferenceException.
Testing
[3,9,20,null,null,15,7]gives3.[1,null,2]gives2.[]gives0.[5]gives1.[1,2,null,3,null,4]gives4.- A chain of 10,000 left children gives
10000.
