Algorithm-Day38-Maximum-Depth-of-Binary-Tree-lc-104
π§© Problem Description
Given the root
of a binary tree, return its maximum depth.
A binary treeβs maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
π¬ Example
1 | Input: root = [3,9,20,null,null,15,7] |
π‘ Approach 1: Recursive DFS
We can recursively compute the depth of left and right subtrees, then take the maximum of the two.
π’ Java Code (Recursive DFS)
1 | class Solution { |
π‘ Approach 2: Iterative BFS (Level Order)
We can use a queue to perform level-order traversal and count how many levels exist.
π’ Java Code (BFS)
1 | class Solution { |
β± Time and Space Complexity
- Time Complexity: O(n) β visit every node once
- Space Complexity:
- Recursive: O(h) call stack
- BFS: O(w) for the queue (w = max width of the tree)
βοΈ Summary
- Depth-first (recursive) is elegant and concise
- Level-order (BFS) gives more control (e.g., per-level info)
- Know both for interviews and practical use
Tree depth is foundational β used in balancing, recursion limits, and more.