0
0
DSA Typescriptprogramming~10 mins

Count Total Nodes in Binary Tree 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 total number of nodes in the binary tree.

DSA Typescript
function countNodes(root: TreeNode | null): number {
  if (root === null) return [1];
  return 1 + countNodes(root.left) + countNodes(root.right);
}
Drag options to blanks, or click blank then click option'
A1
B0
Cnull
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Returning 1 instead of 0 for null nodes.
Returning null which causes errors.
2fill in blank
medium

Complete the code to check if the current node is null before counting.

DSA Typescript
function countNodes(root: TreeNode | null): number {
  if ([1] === null) return 0;
  return 1 + countNodes(root.left) + countNodes(root.right);
}
Drag options to blanks, or click blank then click option'
Anull
Broot.left
Croot.right
Droot
Attempts:
3 left
💡 Hint
Common Mistakes
Checking left or right child instead of the current node.
Checking against a wrong variable.
3fill in blank
hard

Fix the error in the recursive call to count left subtree nodes.

DSA Typescript
function countNodes(root: TreeNode | null): number {
  if (root === null) return 0;
  return 1 + countNodes([1]) + countNodes(root.right);
}
Drag options to blanks, or click blank then click option'
Aroot.right
Bnull
Croot.left
Droot
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the whole root again causing infinite recursion.
Passing right child instead of left child.
4fill in blank
hard

Fill both blanks to complete the function that counts nodes using recursion.

DSA Typescript
function countNodes(root: TreeNode | null): number {
  if ([1] === null) return 0;
  return 1 + countNodes([2]) + countNodes(root.right);
}
Drag options to blanks, or click blank then click option'
Aroot
Broot.left
Croot.right
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Checking left or right child instead of root for null.
Passing wrong child node in recursive call.
5fill in blank
hard

Fill all three blanks to complete the recursive function counting all nodes in the binary tree.

DSA Typescript
function countNodes(root: TreeNode | null): number {
  if ([1] === null) return 0;
  return 1 + countNodes([2]) + countNodes([3]);
}
Drag options to blanks, or click blank then click option'
Aroot
Broot.left
Croot.right
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Using null instead of root for base case.
Mixing left and right child nodes in recursive calls.