Skip to main content

13. Balanced Binary Tree

easyAsked at DigitalOcean

Determine if a binary tree is height-balanced — tests recursive DFS and recognizing when to short-circuit on imbalance.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given a binary tree, determine if it is height-balanced. A height-balanced binary tree is one in which the depth of the two subtrees of every node never differs by more than one.

Constraints

  • Number of nodes in range [0, 5000]
  • -10^4 <= Node.val <= 10^4

Examples

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

Approaches

1. Brute force (top-down)

Compute height for every node separately — O(n log n) due to repeated subtree traversals.

Time
O(n log n)
Space
O(h)
function height(node) {
  if (!node) return 0;
  return 1 + Math.max(height(node.left), height(node.right));
}
function isBalanced(root) {
  if (!root) return true;
  return Math.abs(height(root.left) - height(root.right)) <= 1
    && isBalanced(root.left) && isBalanced(root.right);
}

Tradeoff:

2. Bottom-up DFS with early exit

Return -1 to signal imbalance and propagate it upward, computing height and balance check in a single pass. This avoids redundant traversals.

Time
O(n)
Space
O(h)
function check(node) {
  if (!node) return 0;
  const left = check(node.left);
  if (left === -1) return -1;
  const right = check(node.right);
  if (right === -1) return -1;
  if (Math.abs(left - right) > 1) return -1;
  return 1 + Math.max(left, right);
}
function isBalanced(root) {
  return check(root) !== -1;
}

Tradeoff:

DigitalOcean-specific tips

DigitalOcean likes to extend this to balanced partition checks in distributed systems — be ready to discuss what 'balanced' means for load distribution, not just trees.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Balanced Binary Tree and other DigitalOcean interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →