13. Balanced Binary Tree
easyAsked at UnityDecide if a tree is height-balanced. Unity uses this for BVH-balance checks during physics broadphase rebuilds.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a binary tree, determine if it is height-balanced: at every node the heights of left and right subtrees differ by at most 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. Compute depth at every node
For each node compute left/right depths separately, leading to repeated work.
- Time
- O(n^2)
- Space
- O(h)
const depth = n => n ? 1+Math.max(depth(n.left),depth(n.right)) : 0;
function isBal(n) { return !n || (Math.abs(depth(n.left)-depth(n.right))<=1 && isBal(n.left) && isBal(n.right)); }Tradeoff:
2. DFS sentinel
Return -1 once any subtree is unbalanced; otherwise return the height. Single traversal.
- 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:
Unity-specific tips
Unity grades for single-pass DFS because BVH balance checks during physics broadphase can't afford repeated subtree walks.
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 Unity interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →