Command Palette
Search for a command to run...
Problem 16.1 · Binary TreesEasy
What it teaches: The simplest post-order recursion: depth = 1 + the deeper subtree.
Practise it on judges as “Maximum Depth of Binary Tree”.
The problem
Return the maximum depth of a binary tree: the number of nodes on the longest path from the root to a leaf.
Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: 3
Example 2
Input: root = [1, null, 2]
Output: 2
Constraints
Pattern clues in the wording
- → Answer for a node depends on both subtrees
These clues point to Tree DFS: Recurse into the left and right children and combine what they return (height, sums, paths).
Stuck? Take one hint at a time
Solution.java · starterclass Solution {
public int maxDepth(TreeNode root) {
return 0;
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
Test cases
| # | Input | Expected |
|---|
| 1 | root = [3,9,20,null,null,15,7] | 3 |
| 2 | root = [1,null,2] | 2 |
| 3 | root = [] | 0 |