Skip to problem
←

Balanced Binary Tree

Easy 0 attempts

You're given the root of a binary tree. Determine whether it's height-balanced — meaning that for every node in the tree, the heights of its left and right subtrees differ by at most one.

Function contract

Implement isBalanced(root). The runner converts the level-order array into nodes with val, left, and right fields; [] becomes null.

Output: true if every node’s left and right subtree heights differ by at most one; otherwise false. An empty tree is balanced.

Example 1

Input
root = [3,9,20,null,null,15,7]
Output
true

Example 2

Input
root = [1,2,2,3,3,null,null,4,4]
Output
false

Example 3

Input
root = []
Output
true
Visual Aid
Balanced does not mean identical
3920157Height 1Height 2

The root’s subtree heights differ by 1, and every other node also satisfies the balance condition.

Constraints
  • 0 <= number of nodes <= 5000
  • -10^4 <= Node.val <= 10^4

Iterative Postorder

Compute child heights before parent heights. Reject any node whose child heights differ by more than one.

javascript
function isBalanced(root) {
  if (!root) return true;
  const stack = [[root, false]],
    heights = new Map();
  while (stack.length) {
    const [node, done] = stack.pop();
    if (!done) {
      stack.push([node, true]);
      if (node.right) stack.push([node.right, false]);
      if (node.left) stack.push([node.left, false]);
    } else {
      const l = heights.get(node.left) || 0,
        r = heights.get(node.right) || 0;
      if (Math.abs(l - r) > 1) return false;
      heights.set(node, 1 + Math.max(l, r));
    }
  }
  return true;
}

Time: O(n) | Space: O(n) auxiliary space, excluding output

Loading discussion…

Saved in this browser only. Private to you.

JavaScript