Problem overview
The method maxDepth(_ root: TreeNode?) 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 the farthest leaf. An empty tree, where root is nil, has depth 0. The lesson provides the TreeNode class: each node has a val and optional left and right children.
For the tree [3, 9, 20, nil, nil, 15, 7], written in level order with nil for a missing child, the answer is 3. The path 3 → 20 → 15 has three nodes, and so does 3 → 20 → 7, while 3 → 9 has only two. For [1, nil, 2] the answer is 2, and for the empty tree it is 0.
The follow-up asks for O(n) time, visiting each of the n nodes once.
Approach: a tree is one node deeper than its deeper subtree
A binary tree is a node with two smaller binary trees under it, each possibly empty. That makes the depth easy to define in terms of itself: the depth of a tree is 1, for the root, plus the larger of the depths of its left and right subtrees. This is a natural fit for recursion.
Every recursion needs a base case. Here it is the empty tree, whose depth is 0. A missing child is just a nil tree, so the base case also covers a leaf's two empty children and ends the recursion.
Trace the first example. The depth of each node, from the bottom up, is:
node 9: 1 + max(0, 0) = 1
node 15: 1 + max(0, 0) = 1
node 7: 1 + max(0, 0) = 1
node 20: 1 + max(1, 1) = 2
node 3: 1 + max(1, 2) = 3
Each nil child returns 0, each leaf returns 1, and the answer, 3, comes out at the root. Every node is visited exactly once, which gives O(n) time.
Step by step
- Handle the empty tree. Use
guard let node = root else { return 0 }. This unwraps the optional into a constantnodethat is available for the rest of the function, and theelseblock runs whenrootisnil. The same check stops the recursion when it steps past a leaf. - Find the left depth. Call
maxDepthonnode.leftand store the result inleftDepth. Trust the call to return the depth of the smaller tree, whatever its shape. - Find the right depth the same way, with
node.right. A missing child gives 0 thanks to the base case. - Combine them. Return
1 + max(leftDepth, rightDepth): this node itself, plus the longest path below it.
The solution in Swift
class Solution {
func maxDepth(_ root: TreeNode?) -> Int {
guard let node = root else {
return 0
}
let leftDepth = maxDepth(node.left)
let rightDepth = maxDepth(node.right)
return 1 + max(leftDepth, rightDepth)
}
}
The Swift details worth a closer look:
- Optionals. The parameter is
TreeNode?, so it can benil. Writingroot.leftdirectly is a compile error:value of optional type 'TreeNode?' must be unwrapped to refer to member 'left' of wrapped base type 'TreeNode'. Theguard letunwraps it once, and after thatnodeis a plainTreeNode. guardmust leave the scope. Theelseblock of aguardhas to exit the function, for example withreturn. A block that just prints something is rejected with'guard' body must not fall through, consider using a 'return' or 'throw' to exit the scope.- Recursive calls without
self. Inside a method,maxDepth(node.left)calls the same method on the sameSolutionobject, so noself.is needed. maxis a global function.max(leftDepth, rightDepth)returns the larger of two comparable values, here twoIntvalues.- Child nodes are optionals too.
node.lefthas the typeTreeNode?, which is exactly whatmaxDepthaccepts, so it can be passed on without unwrapping.
Complexity
Time: O(n). The function runs once for each of the n nodes and once for each missing child, which is at most n + 1 more calls. Each call does a constant amount of work.
Space: O(h), where h is the height of the tree, for the recursion's call stack. The statement limits the tree to 400 levels, so the stack stays shallow. For a very unbalanced tree h can reach n, and a tree with a very large n could then exhaust the stack; a chain of 400 nodes is no problem.
Edge cases and common mistakes
- Empty tree.
root = nilreturns 0 from the guard. - A single node. Both children are empty and return 0, so the result is
1 + max(0, 0), which is 1. - A line of nodes.
[1, nil, 2]has one child on the right and none on the left, so the result is1 + max(0, 1), which is 2. A chain of 400 nodes, each the left child of the one above, gives 400. - Returning 1 for the empty tree. That adds one to every answer. The depth counts nodes, so no nodes means 0.
- Adding the two depths.
leftDepth + rightDepthis a different quantity: it is the length of a path that goes down both sides. The depth follows only the longer side, hencemax. - Forgetting to add 1. Without the
1 +, the function returns 0 for every tree, since every path of recursion ends in a base case.
Testing
[3, 9, 20, nil, nil, 15, 7]gives 3.[1, nil, 2]gives 2.[]gives 0.[5]gives 1.[1, 2, nil, 3, nil, 4], a line going down to the left, gives 4.
