Skip to main content

13. Balanced Binary Tree

easyAsked at Slack

Decide whether 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 binary tree is one in which the left and right subtrees of every node differ in height by no more than 1.

Constraints

  • Nodes count in [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. Naive recompute height

At each node, recompute heights of subtrees and compare.

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

Tradeoff:

2. Bottom-up height-sentinel

Return -1 from the subtree if unbalanced, otherwise the height. Propagate -1 upward to short-circuit.

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

Tradeoff:

Slack-specific tips

Slack interviewers grade you on spotting the O(n^2) trap — call out the sentinel value early to avoid a re-do.

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

Practice these live with InterviewChamp.AI →