13. Balanced Binary Tree
easyAsked at SpotifyCheck 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 — for every node, the heights of left and right subtrees differ by at most one.
Constraints
0 <= nodes <= 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. Recompute height per node
For each node compute height of left and right and compare
- Time
- O(n^2)
- Space
- O(h)
function height(n){return n?1+Math.max(height(n.left),height(n.right)):0;}
function bal(n){if(!n)return true;return Math.abs(height(n.left)-height(n.right))<=1 && bal(n.left)&&bal(n.right);}Tradeoff:
2. Single-pass DFS with early exit
Return height or -1 if imbalanced. Propagates failure upward in one O(n) pass.
- 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) return -1;
if (Math.abs(l - r) > 1) return -1;
return 1 + Math.max(l, r);
}
return check(root) !== -1;
}Tradeoff:
Spotify-specific tips
Spotify graders care about avoiding the quadratic recompute trap — flag it explicitly and pivot to the single-pass sentinel technique.
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 Spotify interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →