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 None, has depth 0.
The lesson provides the TreeNode class, where each node has val, left and right, and a missing child is None. Trees are written in level order, top to bottom and left to right, with None for a missing child.
For [3, 9, 20, None, None, 15, 7] 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 each, and 3, 9 has two, so the answer is 3. For [1, None, 2] the only path is 1, 2, so the answer is 2. For [] the answer is 0.
Approach: one more than the deeper subtree
A tree is built from smaller trees: a root with a left subtree and a right subtree. Any longest path starts at the root and then goes down into one of the two subtrees. It goes into the deeper one, so:
depth(tree) = 1 + max(depth(left subtree), depth(right subtree))
The 1 is the root itself. The subtrees are trees too, so the same rule applies to them, which is recursion. It needs a base case, an empty tree, which has depth 0. That also covers the missing children of leaves: a leaf has two empty subtrees, so its depth is 1 + max(0, 0) = 1.
Each node is visited exactly once, so the running time is O(n) for n nodes. The follow-up of the problem asks for this.
Step by step
- Handle the empty tree. If
not rootis true,rootisNone: return 0. This also stops the recursion after it steps past a leaf. - Find the left depth. Call
self.maxDepth(root.left)and store the result inleftDepth. Trust the call to return the right answer for the smaller tree, whatever its shape. - Find the right depth the same way, with
root.right, and store it inrightDepth. A missing child gives 0. - Combine them. Return
1 + max(leftDepth, rightDepth): the root plus the longest path below it.
The solution in Python
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
leftDepth = self.maxDepth(root.left)
rightDepth = self.maxDepth(root.right)
return 1 + max(leftDepth, rightDepth)
Python details worth a closer look:
not root. ATreeNodeobject is always truthy andNoneis falsy, soif not rootis true exactly for an empty tree. A node whosevalis 0 is still truthy, because the test is on the node and not on its value.Optional[TreeNode]. This annotation says the argument is either aTreeNodeorNone. Python doesn't enforce it, so it documents the base case more than it checks anything.- Calling the method recursively. The recursive call goes through
self, as inself.maxDepth(root.left). WritingmaxDepth(root.left)on its own raisesNameError, because inside a method the name isn't in scope. - The recursion limit. Python allows about 1,000 nested calls by default. The tree here is at most 400 levels deep, so the recursion stays well within the limit. A chain of 2,001 nodes would raise
RecursionErrorwith this solution.
Complexity
Time: O(n). Each node is visited once. A node does a constant amount of work besides the two recursive calls: a check, an addition and a comparison. The calls on missing children return immediately, and there are at most n + 1 of them.
Space: O(h), where h is the height of the tree. The call stack holds one frame per level of the path being explored. For a balanced tree that is about log n. For a tree where every node has one child it is n, and the constraint of 400 levels keeps it small here.
Edge cases and common mistakes
- Empty tree.
[]gives 0. Without the base case, the function would tryroot.leftonNoneand raiseAttributeError. - Single node.
[1]gives 1: both children are missing, so the result is1 + max(0, 0). - A tree that is a single chain.
[1, 2, None, 3]has the path 1, 2, 3 going left, so the answer is 3. The right side is empty at every level, and the maximum picks the left. - Counting edges instead of nodes. The depth here counts nodes. The path 3, 20, 15 has 3 nodes and 2 edges, and the expected answer is 3. A base case of
-1would give edge counts. - Using
mininstead ofmax. For[1, None, 2]it would return 1, as the empty left side would win. The longest path is wanted, not the shortest. - Forgetting the
1 +. Without it the function returns 0 for every tree, because only the base case ever produces a number. - Adding the two depths.
leftDepth + rightDepthmeasures a path that goes down one side and up the other, not the depth from the root.
Testing
[3, 9, 20, None, None, 15, 7]gives3.[1, None, 2]gives2.[]gives0.[1]gives1.[1, 2, None, 3]gives3.
