Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new tree node with given data.
DSA C
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = [1];
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning NULL or zero instead of the input data.
Using pointer dereference incorrectly.
✗ Incorrect
The new node's data field should be set to the given data value.
2fill in blank
mediumComplete the code to check if a binary tree node is a leaf node.
DSA C
int isLeaf(struct Node* node) {
return (node->left == NULL && node->right [1] NULL);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using inequality operator instead of equality.
Checking only one child pointer.
✗ Incorrect
A leaf node has both left and right pointers equal to NULL.
3fill in blank
hardFix the error in the code that inserts a node into a binary search tree.
DSA C
struct Node* insert(struct Node* root, int data) {
if (root == NULL) {
return createNode([1]);
}
if (data < root->data) {
root->left = insert(root->left, data);
} else {
root->right = insert(root->right, data);
}
return root;
}Attempts:
3 left
💡 Hint
Common Mistakes
Passing root pointer instead of data value.
Using pointer dereference incorrectly.
✗ Incorrect
When creating a new node, pass the data value, not the root or pointer.
4fill in blank
hardFill both blanks to create a function that counts nodes in a binary tree.
DSA C
int countNodes(struct Node* root) {
if (root == NULL) {
return [1];
}
return 1 + countNodes(root->[2]) + countNodes(root->right);
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning 1 for NULL node.
Using wrong child pointer name.
✗ Incorrect
Return 0 for empty tree; recursively count left subtree nodes.
5fill in blank
hardFill all three blanks to create a function that searches a value in a binary search tree.
DSA C
int searchBST(struct Node* root, int key) {
if (root == NULL) {
return 0;
}
if (key == root->data) {
return 1;
} else if (key [1] root->data) {
return searchBST(root->[2], key);
} else {
return searchBST(root->[3], key);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong comparison operators.
Searching wrong subtree based on comparison.
✗ Incorrect
If key is less, search left subtree; else search right subtree.
