Complete the code to return the height of the tree or -1 if unbalanced.
function checkHeight(node: TreeNode | null): number {
if (node === null) return [1];
// rest of code omitted for brevity
}When the node is null, height is 0 because empty tree has height zero.
Complete the code to check if the left subtree is balanced.
const leftHeight = checkHeight(node.left); if (leftHeight === [1]) return -1;
If left subtree is unbalanced, checkHeight returns -1, so we propagate -1 upwards.
Fix the error in the balance difference check.
if (Math.abs(leftHeight - rightHeight) > [1]) return -1;
The tree is unbalanced if height difference is more than 1.
Fill both blanks to return the height of the current node.
return Math.max([1], [2]) + 1;
The height of current node is max of left and right subtree heights plus one.
Fill all three blanks to complete the isBalanced function.
function isBalanced(root: TreeNode | null): boolean {
return checkHeight([1]) !== [2];
}
function checkHeight(node: TreeNode | null): number {
if (node === null) return [3];
const leftHeight = checkHeight(node.left);
if (leftHeight === -1) return -1;
const rightHeight = checkHeight(node.right);
if (rightHeight === -1) return -1;
if (Math.abs(leftHeight - rightHeight) > 1) return -1;
return Math.max(leftHeight, rightHeight) + 1;
}Call checkHeight on root, return true if result is not -1, and height of null node is 0.
