Balanced Binary Tree

easy

Given the root of a binary tree, return true if it is height-balanced — for every node, the heights of its left and right subtrees differ by at most 1 — and false otherwise.

The tree is given in level-order (breadth-first), using null for missing children.

Hints

A tree is balanced when every node's two subtree heights differ by at most 1.
Naively you'd compute height at every node — that's O(n^2).
Fold the balance check into a single bottom-up height computation for O(n).

Common doubts

It computes height (an O(n) walk) at every one of the n nodes, so the work multiplies to O(n^2) on skewed trees.
It computes each node's height exactly once during a postorder pass and checks the balance condition using the heights already in hand.
Yes — both trivially satisfy the height condition.

Interview follow-ups

Return a sentinel height of -1 to mean 'already unbalanced'; any parent seeing -1 propagates it up without more work.
AVL trees enforce exactly this per-node height condition; red-black trees use a looser black-height invariant.

Fun facts

  • This per-node height condition is precisely the AVL-tree invariant that guarantees O(log n) operations.
  • The -1 sentinel trick turns the balance check into an early-exit recursion that stops at the first violation.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: true
Every node's two subtree heights differ by at most 1.
Example 2
Input: root = [1, 2, 2, 3, 3, null, null, 4, 4]
Output: false
The left child's subtrees have heights 2 and 0 — a difference of 2.
Constraints

- The number of nodes is in the range [0, 5000] - -10^4 <= Node.val <= 10^4

Solve this problem →