class TreeNode {
constructor(val = 0, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function isBalanced(root) {
// Returns [height, balanced] for subtree rooted at node
function check(node) {
if (node === null) return [0, true];
const [leftHeight, leftBalanced] = check(node.left); // check left subtree
const [rightHeight, rightBalanced] = check(node.right); // check right subtree
const height = Math.max(leftHeight, rightHeight) + 1; // current node height
const balanced = leftBalanced && rightBalanced && Math.abs(leftHeight - rightHeight) <= 1; // balanced if subtrees balanced and height diff <=1
return [height, balanced];
}
return check(root)[1];
}
// Driver code using dry_run input
const root = new TreeNode(1,
new TreeNode(2, new TreeNode(4), null),
new TreeNode(3, null, new TreeNode(5))
);
console.log(isBalanced(root) ? "Tree is balanced" : "Tree is not balanced");if (node === null) return [0, true];
base case: empty subtree has height 0 and is balanced
const [leftHeight, leftBalanced] = check(node.left);
recursively check left subtree height and balance
const [rightHeight, rightBalanced] = check(node.right);
recursively check right subtree height and balance
const height = Math.max(leftHeight, rightHeight) + 1;
calculate current node height as max of children plus one
const balanced = leftBalanced && rightBalanced && Math.abs(leftHeight - rightHeight) <= 1;
node is balanced if both subtrees balanced and height difference ≤ 1
return [height, balanced];
return height and balance status up the recursion
final answer is balance status of entire tree