We use a recursive DFS approach. The depth of a node is 1 + max(depth of left child, depth of right child).
- If
rootis None, return 0. - Calculate
left_depth = max_depth(root.left). - Calculate
right_depth = max_depth(root.right). - Return
max(left_depth, right_depth) + 1.
- Time Complexity: O(N).
- Space Complexity: O(H).
def max_depth(root):
if not root:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))