14. Balanced Binary Tree
easyAsked at UdemyDetermine if a binary tree is height-balanced — Udemy uses this to test whether candidates can avoid redundant tree traversals with a bottom-up approach.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a binary tree, determine if it is height-balanced. A height-balanced binary tree is one in which the left and right subtrees of every node differ in height by no more than 1.
Constraints
0 <= number of 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. Brute force top-down
For each node compute height separately, leading to O(n log n) redundant calls.
- Time
- O(n log n)
- Space
- O(h)
function height(node) {
if (!node) return 0;
return 1 + Math.max(height(node.left), height(node.right));
}
function isBalanced(root) {
if (!root) return true;
return Math.abs(height(root.left) - height(root.right)) <= 1
&& isBalanced(root.left) && isBalanced(root.right);
}Tradeoff:
2. Bottom-up DFS
Return -1 from height helper as a sentinel for unbalanced; propagate up so each node is visited once.
- Time
- O(n)
- Space
- O(h)
function isBalanced(root) {
function check(node) {
if (!node) return 0;
const left = check(node.left);
if (left === -1) return -1;
const right = check(node.right);
if (right === -1) return -1;
if (Math.abs(left - right) > 1) return -1;
return 1 + Math.max(left, right);
}
return check(root) !== -1;
}Tradeoff:
Udemy-specific tips
Udemy asks about e-learning recommendation systems, content search, and marketplace algorithms — balanced mix of arrays, hash maps, and dynamic programming problems.
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 Udemy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →