Overview
Given a binary tree, determine if it is height-balanced — a tree where the depth of the two subtrees of every node never differs by more than 1.
Constraints
- The number of nodes is in the range
[0, 5000]. -10^4 <= Node.val <= 10^4- The tree is given as an array in level-order (null for missing nodes).
Examples
isBalanced([3, 9, 20, null, null, 15, 7]); // => true isBalanced([1, 2, 2, 3, 3, null, null, 4, 4]); // => false
Solution
Reveal solution
function isBalanced(root) {
function height(node) {
if (!node) return 0;
const left = height(node.left);
if (left === -1) return -1;
const right = height(node.right);
if (right === -1) return -1;
if (Math.abs(left - right) > 1) return -1;
return Math.max(left, right) + 1;
}
return height(root) !== -1;
}Resources
balanced-binary-tree.js
Balanced Binary Tree
easycodingAlgorithmsBinary Trees
Overview
Given a binary tree, determine if it is height-balanced — a tree where the depth of the two subtrees of every node never differs by more than 1.
Constraints
- The number of nodes is in the range
[0, 5000]. -10^4 <= Node.val <= 10^4- The tree is given as an array in level-order (null for missing nodes).
Examples
isBalanced([3, 9, 20, null, null, 15, 7]); // => true isBalanced([1, 2, 2, 3, 3, null, null, 4, 4]); // => false
Solution
Reveal solution
function isBalanced(root) {
function height(node) {
if (!node) return 0;
const left = height(node.left);
if (left === -1) return -1;
const right = height(node.right);
if (right === -1) return -1;
if (Math.abs(left - right) > 1) return -1;
return Math.max(left, right) + 1;
}
return height(root) !== -1;
}Resources
NameTopicDifficulty
103 of 103 problems