Computing the Maximum Depth of a Binary Tree
Givan a binary tree, the maximum depth is the number of nodes along the longest root‑to‑leaf path. Leaf nodes are those with no children.
Depth‑First Search (Recursive)
The recursive approach computes the depth of the left and right subtreees, then takes the maximum plus one.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def tree_depth(node: TreeNode) -> int:
if node is None:
return 0
left_depth = tree_depth(node.left)
right_depth = tree_depth(node.right)
return max(left_depth, right_depth) + 1
Time complexity: O(n) — each node is visited once.
Space complexity: O(h) where h is the height of the tree, due to the call stack (O(log n) for a balanced tree, O(n) in the worst case).
Breadth‑First Search (Iterative)
A level‑order traversal using a queue counts the number of levels. Each level represents one unit of depth.
from collections import deque
def max_depth_bfs(root: TreeNode) -> int:
if root is None:
return 0
queue = deque([root])
level = 0
while queue:
level += 1
for _ in range(len(queue)):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return level
Time complexity: O(n) — every node is processed once.
Space complexity: O(w) where w is the maximum width of the tree (up to O(n) in the worst case).
Both methods correctly return the maximum depth for any binary tree, including edge cases like an empty tree (depth 0).