Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the height of the tree or -1 if unbalanced.
DSA Typescript
function checkHeight(node: TreeNode | null): number {
if (node === null) return [1];
// rest of code omitted for brevity
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning -1 for null node height causes incorrect balance checks.
✗ Incorrect
When the node is null, height is 0 because empty tree has height zero.
2fill in blank
mediumComplete the code to check if the left subtree is balanced.
DSA Typescript
const leftHeight = checkHeight(node.left); if (leftHeight === [1]) return -1;
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for 0 instead of -1 causes missing unbalanced detection.
✗ Incorrect
If left subtree is unbalanced, checkHeight returns -1, so we propagate -1 upwards.
3fill in blank
hardFix the error in the balance difference check.
DSA Typescript
if (Math.abs(leftHeight - rightHeight) > [1]) return -1;
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 or 2 causes incorrect balance detection.
✗ Incorrect
The tree is unbalanced if height difference is more than 1.
4fill in blank
hardFill both blanks to return the height of the current node.
DSA Typescript
return Math.max([1], [2]) + 1;
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using node.left or node.right instead of their heights causes errors.
✗ Incorrect
The height of current node is max of left and right subtree heights plus one.
5fill in blank
hardFill all three blanks to complete the isBalanced function.
DSA Typescript
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;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning true if checkHeight returns -1 causes wrong result.
Returning -1 for null node height causes errors.
✗ Incorrect
Call checkHeight on root, return true if result is not -1, and height of null node is 0.