Recursive DFS
Intuition
The simplest way to find the maximum depth is through recursion. At each node, the depth equals one plus the maximum depth of its left and right subtrees. The base case is a null node, which has depth zero. This naturally explores every path from root to leaf and returns the longest one. The recursion mirrors the tree structure itself, making it intuitive to reason about.
Algorithm
- If the root is null, return 0.
- Recursively compute the maximum depth of the left subtree.
- Recursively compute the maximum depth of the right subtree.
- Return 1 + max(leftDepth, rightDepth).
O(n)SpaceO(h) where h is the height of the tree (O(n) in the worst case for a skewed tree)Code (C++ · Java · Python · Go)
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}def maxDepth(root: Optional[TreeNode]) -> int:
if not root:
return 0
return 1 + max(maxDepth(root.left), maxDepth(root.right))func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
left := maxDepth(root.Left)
right := maxDepth(root.Right)
if left > right {
return 1 + left
}
return 1 + right
}