Problem Statement in English
You’re given the root of a binary tree. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Approach
We can use a recursive depth-first search (DFS) approach to traverse the binary tree and calculate the maximum depth.
The idea is to explore each node, and for each node, we will calculate the depth of its left and right subtrees.
The maximum depth of the current node will be 1 (for the current node itself) plus the maximum depth of its left and right children.
And we’re done!
Solution in Python
class Solution:
def maxDepth(self, root: TreeNode | None) -> int:
if not root: return 0
def dfs(node):
if not node.left and not node.right:
return 1
height = 0
if node.left:
height = 1 + dfs(node.left)
if node.right:
height = max(height, 1 + dfs(node.right))
return height
return dfs(root)
Complexity
Time: $O(n)$
Since we are visiting each node once, the time complexity is linear with respect to the number of nodes in the tree.Space: $O(h)$
where $h$ is the height of the tree. This space is used by the recursion stack during the depth-first search. In the worst case, for a skewed tree, the height can be equal to the number of nodes, leading to a space complexity of $O(n)$. In a balanced tree, the height would be $O(\log n)$.
And we are done.