Maximum Depth of Binary Tree
Maximum Depth of Binary Tree
Section titled “Maximum Depth of Binary Tree”
Easy
Day 13 • Striver Blind 75
📌 Problem Overview
Section titled “📌 Problem Overview”Given the root of a binary tree, return its maximum depth (the number of nodes on the longest root-to-leaf path).
Examples & Constraints
Section titled “Examples & Constraints”Example 1:
- Input:
root = [3,9,20,null,null,15,7] - Output:
3
Example 2:
- Input:
root = [1,null,2] - Output:
2
Constraints:
0 ≤ tree nodes ≤ 10⁴
💡 Approach & Intuition
Section titled “💡 Approach & Intuition”The foundational tree problem introducing tree traversal and recursive thinking.
🎯 Pattern Recognition
Section titled “🎯 Pattern Recognition”Pattern: Tree Recursion
Solve for the left subtree, solve for the right subtree, then combine the results.
📊 Step-by-Step Execution (Mermaid Diagram)
Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”graph TD Root["TreeNode (Root)"] -->|Recurse Left| Left["Left Subtree"] Root -->|Recurse Right| Right["Right Subtree"] Left --> Base1{"Base Case (null)"} Right --> Base2{"Base Case (null)"} Base1 --> Combine["Combine Results"] Base2 --> Combine Combine --> Ans["Return Root Value / Depth"]🐢 Brute Force Solution
Section titled “🐢 Brute Force Solution”// Recursive DFS is standard- Time Complexity:
O(n) - Space Complexity:
O(h) - Explanation: DFS recursion.
⚡ Optimized Solution
Section titled “⚡ Optimized Solution”function maxDepth(root) { if (!root) return 0; return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));}- Time Complexity:
O(n) - Space Complexity:
O(h) - Explanation: Recursive DFS.
🐾 Step-by-Step Walkthrough
Section titled “🐾 Step-by-Step Walkthrough”- Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
- Iterate & Evaluate: Process the input according to the boundary conditions.
- Update & Return: Compute the optimal answer and return early or at termination.
🎙️ FAANG Interview Pitch
Section titled “🎙️ FAANG Interview Pitch”- Base case: empty tree depth 0
- Node depth = 1 + max(left, right)
- Classic divide-and-conquer on trees
💡 Progressive Hints
Section titled “💡 Progressive Hints”- Depth of empty tree is 0.
- Depth of a node = 1 + max(depth of left, depth of right).
- Use recursion.