13. Balanced Binary Tree
easyAsked at TripAdvisorDetermine if a binary tree is height-balanced.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
Given a binary tree, determine if it is height-balanced. A height-balanced binary tree is defined as one in which the left and right subtrees of every node differ in height by no more than 1.
Constraints
0 <= nodes <= 5000-10^4 <= Node.val <= 10^4
Examples
Example 1
Input
root = [3,9,20,null,null,15,7]Output
trueExample 2
Input
root = [1,2,2,3,3,null,null,4,4]Output
falseApproaches
1. Recompute height per node
For each node, compute heights of both subtrees independently.
- Time
- O(n^2)
- Space
- O(h)
const height = (n) => n ? 1 + Math.max(height(n.left), height(n.right)) : 0;
const check = (n) => !n || (Math.abs(height(n.left) - height(n.right)) <= 1 && check(n.left) && check(n.right));
return check(root);Tradeoff:
2. Bottom-up DFS with sentinel
Return -1 from unbalanced subtree so we short-circuit. Each node visited once.
- 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:
TripAdvisor-specific tips
TripAdvisor uses balanced-tree checks as a proxy for spotting skewed category trees in tag taxonomies.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
More TripAdvisor coding interview questions
- 1. Two Sum
- 2. Valid Parentheses
- 3. Merge Two Sorted Lists
- 4. Remove Duplicates from Sorted Array
- 5. Remove Element
- 6. Search Insert Position
- 7. Plus One
- 8. Merge Sorted Array