EasyTrees
Maximum Depth of Binary Tree
Find max depth of tree
Solution Approach
Use DFS recursion or BFS with queue. Maximum depth is 1 + max depth of subtrees.
Implementation
def maxDepth(root):
if not root:
return 0
return 1 + max(maxDepth(root.left), maxDepth(root.right))
# BFS approach
from collections import deque
def maxDepthBFS(root):
if not root:
return 0
queue = deque([(root, 1)])
while queue:
node, depth = queue.popleft()
if not node:
continue
if not node.left and not node.right:
return depth
if node.left:
queue.append((node.left, depth + 1))
if node.right:
queue.append((node.right, depth + 1))
return 0Complexity Analysis
Time Complexity
O(n)Space Complexity
O(h)Complexity
Time:O(n)
Space:O(h)
Asked at
GoogleAmazonFacebook