Command Palette
Search for a command to run...
Problem 16.6 · Binary TreesEasy
What it teaches: Return a sentinel (−1) up the tree as soon as a subtree is unbalanced, keeping it O(n).
Practise it on judges as “Balanced Binary Tree”.
The problem
A tree is height-balanced if, at every node, the heights of the two subtrees differ by at most 1. Return whether the tree is balanced.
Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: true
Example 2
Input: root = [1, 2, 2, 3, 3, null, null, 4, 4]
Output: false
Constraints
Pattern clues in the wording
- → A property checked at every node, using subtree heights
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 boolean isBalanced(TreeNode root) {
return true;
}
}
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] | true |
| 2 | root = [1,2,2,3,3,null,null,4,4] | false |
| 3 | root = [] | true |
+ 1 hidden test the code runner will check