EASY NC#47 Blind #60 Trees
104. Maximum Depth of Binary Tree
๐ Problem
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.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขRecursive stack flow
- โขCycle prevention
- โขPost-order reasoning
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply DFS reasoning pattern
- โขApply BFS reasoning pattern
- โขApply Recursion reasoning pattern
๐ก Approach
- โ Use DFS recursively to find maximum depth
- โ Base case: null node has depth 0
- โ Max depth = 1 + max(depth of left, depth of right)
- โ Time: O(n), Space: O(h) where h is tree height
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse DFS recursively to find maximum depth
- โขBase case: null node has depth 0
- โขMax depth = 1 + max(depth of left, depth of right)
Common Pitfalls
- โขTime: O(n), Space: O(h) where h is tree height
๐งช Test Cases
Hidden tests on submit: 3
Test Case 1
Not run Input:
maxDepth(buildTree([3,9,20,null,null,15,7])); Expected:
3 Test Case 2
Not run Input:
maxDepth(buildTree([1,null,2])); Expected:
2 Test Case 3
Not run Input:
maxDepth(buildTree([])); Expected:
0 ๐ Code Editor
๐ค Output