Hint: Add 1 for current node plus children counts [OK]
Common Mistakes:
Counting only root node
Ignoring one child subtree
Returning zero for non-null root
4. Find the error in this code snippet for counting nodes in a binary tree:
int countNodes(Node* root) {
if (root == nullptr) return 0;
return countNodes(root->left) + countNodes(root->right);
}
medium
A. Missing addition of 1 for current node
B. Base case returns 1 instead of 0
C. Function does not handle nullptr correctly
D. No error, code is correct
Solution
Step 1: Check base case correctness
Base case returns 0 for nullptr, which is correct.
Step 2: Check counting logic
The function sums counts of left and right subtrees but does not add 1 for the current node itself, missing counting the root.
Final Answer:
Missing addition of 1 for current node -> Option A
Quick Check:
Count must include current node [OK]
Hint: Add 1 for current node in return [OK]
Common Mistakes:
Returning 1 for null node
Not adding 1 for current node
Confusing base case return value
5. Given a binary tree where each node has either 0 or 2 children, and the total number of leaf nodes is 7, what is the total number of nodes in the tree?
hard
A. 14
B. 13
C. 15
D. 16
Solution
Step 1: Recall property of full binary trees
In a full binary tree (nodes have 0 or 2 children), total nodes = 2 * leaf nodes - 1.
Step 2: Calculate total nodes
Given leaf nodes = 7, total nodes = 2 * 7 - 1 = 13.
Step 3: Verify formula and options
Formula: total nodes = 2 * leaf nodes - 1 = 2*7 -1 = 13, which matches 13.
Final Answer:
13 -> Option B
Quick Check:
Full binary tree nodes = 2*leaves - 1 [OK]
Hint: Use full tree formula: nodes = 2*leaves - 1 [OK]
Common Mistakes:
Using wrong formula for total nodes
Confusing leaf nodes with total nodes
Selecting option without calculation
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.