Problem overview
The function maxDepth receives root, a pointer to the top node of a binary tree, and returns the tree's maximum depth: the number of nodes on the longest path from the root down to a leaf. An empty tree, where root is nil, has depth 0. The lesson provides the TreeNode type, with an integer Val and two pointers, Left and Right, that are nil when a child is missing.
For the tree with root 3, whose left child is 9 and whose right child is 20 with children 15 and 7, the answer is 3. The paths 3, 20, 15 and 3, 20, 7 have three nodes each, and the path 3, 9 has two. For a root 1 with a single right child 2 the answer is 2, and for an empty tree it is 0.
The follow-up asks for O(n) time, visiting each of the n nodes once.
Approach: one node deeper than the deeper subtree
A tree is built from smaller trees. The depth of a tree with a root is 1 (the root itself) plus the depth of whichever subtree is deeper. The subtrees are trees too, and they follow the same rule, so the problem calls for recursion.
Every recursion needs a base case, a case so small that the answer is known. Here it is the empty tree. A nil pointer has depth 0. This also covers missing children: stepping from a leaf to its nil child returns 0 and ends that branch.
Each node is handled once, so the work is proportional to the number of nodes.
Step by step
- Handle the empty tree. If
root == nil, return 0. This is both the answer for an empty input and the stopping point for every branch of the recursion. - Find the left depth. Call
maxDepth(root.Left)and store it inleftDepthwith:=. You don't need to know how the call works inside. It returns the depth of the smaller tree under the left child, whatever its shape. - Find the right depth the same way with
root.Right. A missing child gives 0, because of the base case. - Combine. Return 1 plus the larger of the two depths. The 1 counts the root, and the larger depth is the longest path below it.
The solution in Go
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
leftDepth := maxDepth(root.Left)
rightDepth := maxDepth(root.Right)
return 1 + max(leftDepth, rightDepth)
}
On the first example, the call for the root 3 asks for the depths of its subtrees. The subtree rooted at 9 has depth 1, because both of its children are nil. The subtree rooted at 20 has depth 2, and the call on the root returns 1 + max(1, 2), which is 3. Running the function on the three examples gives 3, 2 and 0.
Go details
- Reading a field of
nilpanics. The function checksroot == nilbefore touchingroot.Left. Reading a field of anilpointer panics, so without that check the recursion would crash at the first leaf. - Built-in
max. Since Go 1.21,maxis part of the language and works for numbers and strings. Before that, you had to write your own helper function. - Pointers need no dereferencing syntax.
root.Leftworks on a*TreeNodedirectly; Go follows the pointer for you. - Recursion depth. Go grows a goroutine's stack as needed, so a chain of 100,000 nodes still returns 100000. The lesson's trees have at most 400 levels, which is no problem.
Complexity
Time: O(n). Each node is visited by exactly one call, and each call does a fixed amount of work besides its two recursive calls. The nil children add at most n + 1 further calls that return at once.
Space: O(h), where h is the tree's height. The recursion keeps one frame per level of the path being explored, so a balanced tree uses about log n frames and a chain uses n. The function creates no data structures of its own.
Edge cases and common mistakes
- Empty tree.
maxDepth(nil)returns 0. - A single node. Both children are
nil, so the result is1 + max(0, 0), which is 1. - A chain. A tree where every node has only a left child, with four nodes, has depth 4. The shallow side of each node contributes 0 and the deep side decides.
- Counting edges instead of nodes. This problem counts nodes, so a single node has depth 1, not 0.
- Forgetting the
1 +. Without it the function always returns 0. - Using the smaller depth, or adding the two. The depth of a node is 1 plus the larger of the two subtree depths, not their sum.
- Skipping the
nilcheck and then readingroot.Lefton an empty tree, which panics.
Testing
[3, 9, 20, nil, nil, 15, 7]gives3.[1, nil, 2]gives2.[]gives0.- A single node gives
1. - A chain of four nodes, each the left child of the one above, gives
4.
