Balanced Binary Tree
Difficulty: Easy
You're given the root of a binary tree. Return true if it's height-balanced: at every node, the heights of the left and right subtrees differ by at most 1. Return false if any node breaks this.
Examples
Input: root = [3,9,20,null,null,15,7]
Output: true
Checking every node, the left and right subtree heights never differ by more than 1.
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
The subtree rooted at the first '2' has a left height of 2 and a right height of 0 - a difference of 2, which breaks the balance rule.
Input: root = []
Output: true
An empty tree is trivially balanced - there are no nodes to violate the rule.
Constraints
The number of nodes in the tree is in the range [0, 5000].
-10^4 <= Node.val <= 10^4
Approach
A naive approach checks balance at the root, then recomputes heights to check every subtree again. The repeated height work makes it slow.
Instead, do both in one recursive pass. A helper computes a subtree's height, but if it finds an imbalance below, it returns a sentinel (like -1) instead of a real height. Any parent that sees the sentinel passes it straight up, so one bottom-up pass is enough.
Solutions
Brute Force — Height Recomputed at Every Node
At each node, compute both subtree heights with separate recursive calls and check they differ by at most 1. Then check both children the same way.
class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function height(node) {
if (node === null) return 0;
return 1 + Math.max(height(node.left), height(node.right));
}
function isBalanced(root) {
if (root === null) return true;
const diff = Math.abs(height(root.left) - height(root.right));
if (diff > 1) return false;
return isBalanced(root.left) && isBalanced(root.right);
}Time: O(n²) — height() recomputes overlapping subtree heights at every node · Space: O(h) — recursion stack depth
Optimal — Height + Balance Check in One Pass
A helper returns a subtree's height, or -1 as soon as it finds an imbalance below. Any call that gets -1 from a child passes it up, so one pass covers the whole tree.
function isBalanced(root) {
function height(node) {
if (node === null) return 0;
const leftHeight = height(node.left);
if (leftHeight === -1) return -1;
const rightHeight = height(node.right);
if (rightHeight === -1) return -1;
if (Math.abs(leftHeight - rightHeight) > 1) return -1;
return 1 + Math.max(leftHeight, rightHeight);
}
return height(root) !== -1;
}Time: O(n) · Space: O(h) — recursion stack depth, where h is the tree's height (O(n) worst case)