Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to count nodes recursively in a binary tree.
DSA C
int countNodes(struct Node* root) {
if (root == NULL) {
return 0;
}
return 1 + countNodes(root->[1]) + countNodes(root->right);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using root->right instead of root->left in the first recursive call.
Using an invalid field name like root->child.
✗ Incorrect
The left child of the root is accessed by root->left to count nodes in the left subtree.
2fill in blank
mediumComplete the code to count nodes recursively in a binary tree.
DSA C
int countNodes(struct Node* root) {
if (root == NULL) {
return 0;
}
return 1 + countNodes(root->left) + countNodes(root->[1]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using root->left instead of root->right in the second recursive call.
Using an invalid field name like root->child.
✗ Incorrect
The right child of the root is accessed by root->right to count nodes in the right subtree.
3fill in blank
hardFix the error in the base case to correctly count nodes in a binary tree.
DSA C
int countNodes(struct Node* root) {
if (root == [1]) {
return 0;
}
return 1 + countNodes(root->left) + countNodes(root->right);
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking if root == 0 instead of root == NULL.
Checking if root == false or root == root.
✗ Incorrect
The base case checks if the root pointer is NULL, meaning no node exists there.
4fill in blank
hardFill both blanks to complete the iterative approach to count nodes using a queue.
DSA C
int countNodesIterative(struct Node* root) {
if (root == NULL) return 0;
int count = 0;
struct Queue* q = createQueue();
enqueue(q, root);
while (!isEmpty(q)) {
struct Node* current = dequeue(q);
count++;
if (current->[1] != NULL) enqueue(q, current->[1]);
if (current->[2] != NULL) enqueue(q, current->[2]);
}
return count;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using invalid fields like parent or child.
Checking only one child and missing nodes.
✗ Incorrect
We check both left and right children of the current node to enqueue them for counting.
5fill in blank
hardFill all three blanks to complete the recursive function that counts nodes and prints the count.
DSA C
#include <stdio.h> int countNodes(struct Node* [1]) { if ([1] == NULL) return 0; return 1 + countNodes([1]->left) + countNodes([1]->[2]); } int main() { struct Node* root = createSampleTree(); int total = countNodes(root); printf("Total nodes: %[3]d\n", total); return 0; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong parameter names like node.
Using wrong format specifier in printf.
✗ Incorrect
The function parameter is root; we count right child nodes with root->right; %d is the format specifier for integers.
