Determine whether a binary tree is height-balanced.
Given the root of a binary tree, determine whether it is height-balanced.
A binary tree is considered height-balanced if, for every node, the heights of the left and right subtrees differ by at most 1.
Return true if the tree is balanced, and false otherwise.
Input Format
- A binary tree root node is provided as the input.
- Each node has up to two children:
leftandright.
Output Format
- Return a boolean value.
trueif the tree is height-balanced, otherwisefalse.
Constraints
- The tree may be empty.
- Check the height-balance condition for every node.
- Aim for a solution better than repeatedly recomputing subtree heights.
Example 1
Input
root = [3,9,20,null,null,15,7]
Output
true
Explanation
The left subtree has height 1 and the right subtree has height 2. Every node satisfies the balance condition.
Example 2
Input
root = [1,2,2,3,3,null,null,4,4]
Output
false
Explanation
Node 2 on the left has left and right subtree heights that differ by more than 1, so the tree is not balanced.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.