0
0
DSA Javascriptprogramming~10 mins

Count Total Nodes in Binary Tree in DSA Javascript - 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 Javascript
function countNodes(root) {
  if (root === null) return [1];
  return 1 + countNodes(root.left) + countNodes(root.right);
}
Drag options to blanks, or click blank then click option'
A0
Bnull
C1
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Returning 1 instead of 0 for null nodes.
Returning null which causes errors in addition.
2fill in blank
medium

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

DSA Javascript
function countNodes(root) {
  if (root [1] null) return 0;
  return 1 + countNodes(root.left) + countNodes(root.right);
}
Drag options to blanks, or click blank then click option'
A!==
B===
C!=
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using == which allows type coercion.
Using != or !== which check inequality.
3fill in blank
hard

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

DSA Javascript
function countNodes(root) {
  if (root === null) return 0;
  return 1 + countNodes(root.[1]) + countNodes(root.right);
}
Drag options to blanks, or click blank then click option'
Aleftt
Bnode
Cright
Dleft
Attempts:
3 left
💡 Hint
Common Mistakes
Typo in 'left' as 'leftt'.
Using 'right' instead of 'left'.
4fill in blank
hard

Fill both blanks to complete the function that counts nodes recursively.

DSA Javascript
function countNodes(root) {
  if (root [1] null) return [2];
  return 1 + countNodes(root.left) + countNodes(root.right);
}
Drag options to blanks, or click blank then click option'
A===
B==
C0
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using loose equality (==) instead of strict (===).
Returning 1 instead of 0 for null nodes.
5fill in blank
hard

Fill all three blanks to create a concise recursive count of nodes.

DSA Javascript
const countNodes = (root) => {
  if (root [1] null) return [2];
  return 1 + countNodes(root.[3]) + countNodes(root.right);
};
Drag options to blanks, or click blank then click option'
A===
B0
Cleft
D!==
Attempts:
3 left
💡 Hint
Common Mistakes
Using !== instead of === for null check.
Returning 1 instead of 0 for null.
Typo in 'left' property.