Maximum Depth of Binary Tree
LeetCode 104 · Easy · solution, intuition & step-by-step walkthrough
depth = 1 + max(depth(left), depth(right)).
This is how I solved Maximum Depth of Binary Tree (LeetCode 104), an easy problem from the DFS Basics pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
A tree's depth is one more than the deeper of its two subtrees; an empty tree has depth 0.
Approach
- 1
Empty → 0.
- 2
Recurse on both children.
- 3
Return 1 + the larger.
How I solved it
Post-order recursionPythonO(n) time · O(h) space
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
def dfs(node):
if node==None:
return 0
left = max(0,dfs(node.left))
right = max(0,dfs(node.right))
return 1+max(left,right)
return dfs(root)
Maximum Depth of Binary Tree — FAQ
What is the intuition behind Maximum Depth of Binary Tree?
A tree's depth is one more than the deeper of its two subtrees; an empty tree has depth 0.
How do you solve Maximum Depth of Binary Tree (LeetCode 104)?
1. Empty → 0. 2. Recurse on both children. 3. Return 1 + the larger.
What is the time and space complexity of Maximum Depth of Binary Tree?
Time: O(n). Space: O(h). (Accepted approach: Post-order recursion.)
What are common mistakes in Maximum Depth of Binary Tree?
BFS by levels gives the same answer iteratively.