13. Balanced Binary Tree
easyAsked at TeslaDetermine if a binary tree is height-balanced.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the root of a binary tree, return true if it is height-balanced — for every node, the heights of left and right subtrees differ by at most 1.
Constraints
0 <= node count <= 5000-10^4 <= node.val <= 10^4
Examples
Example 1
root = [3,9,20,null,null,15,7]trueExample 2
root = [1,2,2,3,3,null,null,4,4]falseApproaches
1. Top-down height recomputed
Compute height at every node, recurse.
- Time
- O(n^2)
- Space
- O(h)
function height(n){ return n ? 1 + Math.max(height(n.left), height(n.right)) : 0; }
function isBal(n){ if(!n) return true; return Math.abs(height(n.left)-height(n.right)) <= 1 && isBal(n.left) && isBal(n.right); }Tradeoff:
2. Bottom-up single pass
Return height or -1 sentinel; bail when any subtree is unbalanced.
- Time
- O(n)
- Space
- O(h)
function isBalanced(root) {
const 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:
Tesla-specific tips
Tesla wants the bottom-up sentinel that avoids the O(n^2) trap — same idea as bailing on a planner branch the instant a subtree fails its real-time deadline.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Balanced Binary Tree and other Tesla interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →