0
0
DSA Typescriptprogramming~10 mins

Check if Binary Tree is Balanced in DSA Typescript - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A0
B-1
Cnull
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Returning -1 for null node height causes incorrect balance checks.
2fill in blank
medium

Complete 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'
A0
Bnull
C1
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for 0 instead of -1 causes missing unbalanced detection.
3fill in blank
hard

Fix 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'
A1
B0
C2
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 or 2 causes incorrect balance detection.
4fill in blank
hard

Fill 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'
AleftHeight
BrightHeight
Cnode.left
Dnode.right
Attempts:
3 left
💡 Hint
Common Mistakes
Using node.left or node.right instead of their heights causes errors.
5fill in blank
hard

Fill 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'
Aroot
B-1
C0
Dnode
Attempts:
3 left
💡 Hint
Common Mistakes
Returning true if checkHeight returns -1 causes wrong result.
Returning -1 for null node height causes errors.