Hint: Add 1 for root plus counts of left and right [OK]
Common Mistakes:
Counting only leaf nodes
Forgetting to add root node
Miscounting subtree nodes
4. Find the error in this node counting function and select the correct fix:
int countNodes(Node* root) {
if (root == NULL) return 1;
return countNodes(root->left) + countNodes(root->right);
}
medium
A. Both A and B are needed
B. Add +1 to the return statement to count current node
C. Change base case return to 0 instead of 1
D. No error, function is correct
Solution
Step 1: Check base case return value
Returning 1 for NULL node is wrong; should return 0.
Step 2: Check counting current node
Function misses counting current node; add +1 to sum of children.
Final Answer:
Both A and B are needed -> Option A
Quick Check:
Base case 0 + count current node 1 [OK]
Hint: Base case 0 + add 1 for current node [OK]
Common Mistakes:
Returning 1 for NULL node
Not adding 1 for current node
Assuming function is correct without base case
5. Given a binary tree where some nodes have only one child, how would you modify the counting function to count only nodes that have at least one child?
hard
A. Count nodes with two children only
B. Count all nodes including leaf nodes
C. Count only leaf nodes with no children
D. Count nodes where left or right child is not NULL, skip leaf nodes
Solution
Step 1: Identify nodes with children
Check if node's left or right child is not NULL to confirm it has children.
Step 2: Count only nodes with children
Return 1 for nodes with children plus recursive counts; skip leaf nodes.
Final Answer:
Count nodes where left or right child is not NULL, skip leaf nodes -> Option D
Quick Check:
Count nodes with children only [OK]
Hint: Count nodes having at least one child only [OK]
Common Mistakes:
Counting leaf nodes mistakenly
Counting only nodes with two children
Ignoring nodes with one child
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.