Maximum Depth of Binary Tree — DFS and BFS Approaches
Advertisement
Problem 346 · Maximum Depth of Binary Tree
Difficulty: Easy · Pattern: DFS / BFS
Solutions
// C
int maxDepth(struct TreeNode* root) {
if (!root) return 0;
int l = maxDepth(root->left), r = maxDepth(root->right);
return 1 + (l>r?l:r);
}
// C++
int maxDepth(TreeNode* root) {
if (!root) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
// Java
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
# Python — recursive
def maxDepth(root):
if not root: return 0
return 1 + max(maxDepth(root.left), maxDepth(root.right))
# BFS
from collections import deque
def maxDepthBFS(root):
if not root: return 0
queue = deque([root]); depth = 0
while queue:
depth += 1
for _ in range(len(queue)):
node = queue.popleft()
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
return depth
Complexity
- Time: O(n)
- Space: O(h) where h = height (O(n) worst, O(log n) balanced)
Advertisement