13. Balanced Binary Tree
easyAsked at CanvaDecide whether a binary tree is height-balanced — Canva uses this to test bottom-up recursion versus naive top-down recomputation.
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 the two subtrees differ by no more than 1.
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. Top-down depth
At each node compute depth of both children; recomputes work.
- 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){if(!n)return true;return Math.abs(depth(n.left)-depth(n.right))<=1 && bal(n.left) && bal(n.right);}Tradeoff:
2. Bottom-up depth with short-circuit
Return -1 from a subtree once imbalance found; otherwise return height. Single O(n) pass.
- 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:
Canva-specific tips
Canva interviewers like the early-exit sentinel pattern because it mirrors how their renderer aborts traversal at the first invalid layer.
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 Canva interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →