Skip to main content

13. Balanced Binary Tree

easyAsked at Zoom

Determine if a binary tree is height-balanced.

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

Problem

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

Constraints

  • 0 <= nodes <= 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. Naive depth per node

Compute depth twice for each subtree.

Time
O(n^2)
Space
O(h)
function depth(n){return n?1+Math.max(depth(n.left),depth(n.right)):0;}
function bal(n){return !n || (Math.abs(depth(n.left)-depth(n.right))<=1 && bal(n.left)&&bal(n.right));}

Tradeoff:

2. Single-pass with sentinel

Return -1 from recursion on imbalance to short-circuit.

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

Tradeoff:

Zoom-specific tips

Zoom favors candidates who collapse two passes into one when discussing how the SDK keeps participant-tree balance checks within a single frame budget.

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 Zoom interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →