13. Balanced Binary Tree
easyAsked at EtsyDecide whether a tree is height-balanced — Etsy uses it to test pruning vs. naive double-recursion.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a binary tree, determine if it is height-balanced — every node's two subtrees differ in height by at most 1.
Constraints
Node count in [0, 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. Compute heights at each node
For each node, recompute left and right heights — recomputes a lot.
- 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 with sentinel
Return height up the tree; return -1 to short-circuit imbalance.
- 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:
Etsy-specific tips
Etsy will reward the O(n) bottom-up solution explicitly — show you noticed the quadratic trap before they hint at it.
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 Etsy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →