#24EasyTrees

Maximum Depth of Binary Tree

Given the `root` of a binary tree, return its maximum depth — the number of nodes along the longest path from the root down to the farthest leaf node. **Core Insight:** The maximum depth of a tree is 1 (for the root itself) plus the maximum depth of its deeper subtree. This is a natural recursive definition. The base case is a null node, which has depth 0. **Algorithm (recursive DFS):** If `root` is null return 0. Otherwise return `1 + max(maxDepth(root.left), maxDepth(root.right))`. **Algorithm (iterative BFS):** Use a queue. Process level by level, incrementing a depth counter for each level. Return the counter after the queue is empty. **Which to use:** Recursion is more concise. BFS is preferred when the tree is very deep (to avoid stack overflow) or when you need level-by-level information. **Complexity:** Time O(n) — every node is visited once. Space O(h) for recursion stack (h = tree height), O(n) worst case for a skewed tree.

Constraints

  • The number of nodes is in the range [0, 10⁴]
Solution inPython
Python
def maxDepth(root) -> int:
    if not root:
        return 0
    return 1 + max(maxDepth(root.left), maxDepth(root.right))