Is the tree height-balanced?
Standard · Write code · about 15 min
A binary tree is height-balanced when, at every node, the heights of the left and right subtrees differ by at most 1. Return true if the tree with the given root is height-balanced and false otherwise. An empty tree is balanced.
Example 1
Input:
[[3,9,20,null,null,15,7]]
Output:
true
At 3 the subtree heights are 1 and 2.
Example 2
Input:
[[1,2,2,3,3,null,null,4,4]]
Output:
false
At the root the heights are 3 and 1.
Constraints
- 0 ≤ number of nodes ≤ 1,000
- -1,000 ≤ node value ≤ 1,000
- The tree is given in level order; null marks a missing child
Learn the idea first: Why balance matters, a visual lesson.
More Why balance matters problems
- Height after sorted inserts Warm-up
- Cost of search in a chain Warm-up
- Choose an insertion order for balance Standard
- Height of a tree Standard
- Build a balanced BST from a sorted array Challenge