154. Balanced Binary Tree

Easy · Binary Tree

Given a binary tree, determine if it is height-balanced. A height-balanced binary tree is defined as a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

The tree is encoded as a level-order array where each element represents a node value, and null represents a missing node. For example, [3, 9, 20, null, null, 15, 7] represents a tree where 3 is the root, 9 is the left child, 20 is the right child, 15 is the left child of 20, and 7 is the right child of 20.

Examples

Example 1
Input: [3, 9, 20, null, null, 15, 7]
Output: true
Explanation: The tree is balanced. The left subtree (node 9) has height 0, and the right subtree (node 20 with children 15 and 7) has height 1. The difference is 1, which satisfies the balance condition. All subtrees are also balanced.
Example 2
Input: [1, 2, 2, 3, 3, null, null, 4, 4]
Output: false
Explanation: The tree is not balanced. The left subtree of the root has height 2 (node 2 with left child 3 which has children 4 and 4), while the right subtree has height 0 (node 2 with no children). The difference is 2, which violates the balance condition.

Constraints