Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to perform an inorder traversal of the BST.
DSA C
void inorderTraversal(struct Node* root) {
if (root == NULL) return;
inorderTraversal(root->left);
printf("%d ", root->[1]);
inorderTraversal(root->right);
}Attempts:
3 left
💡 Hint
Common Mistakes
Printing the left or right pointer instead of the node's value.
Trying to print a non-existent field like 'parent'.
✗ Incorrect
In inorder traversal, we print the value stored in the node, which is accessed by 'data'.
2fill in blank
mediumComplete the code to count nodes during inorder traversal to find the kth smallest element.
DSA C
void kthSmallestUtil(struct Node* root, int k, int* count, int* result) {
if (root == NULL) return;
kthSmallestUtil(root->left, k, count, result);
(*count)++;
if (*count == [1]) {
*result = root->data;
return;
}
kthSmallestUtil(root->right, k, count, result);
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing count with result or root instead of k.
Using the wrong variable in the if condition.
✗ Incorrect
We compare the current count with k to find the kth smallest element.
3fill in blank
hardFix the error in the function that returns the kth smallest element in the BST.
DSA C
int kthSmallest(struct Node* root, int k) {
int count = 0;
int result = -1;
kthSmallestUtil(root, k, &count, &[1]);
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Passing &count instead of &result.
Passing the variable itself instead of its address.
✗ Incorrect
The address of 'result' must be passed to store the kth smallest element.
4fill in blank
hardFill both blanks to complete the insertion function for BST.
DSA C
struct Node* insert(struct Node* root, int key) {
if (root == NULL) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = key;
temp->left = NULL;
temp->right = NULL;
return temp;
}
if (key [1] root->data) {
root->left = insert(root->left, key);
} else if (key [2] root->data) {
root->right = insert(root->right, key);
}
return root;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using <= or >= which can cause duplicates on one side.
Swapping the comparison operators.
✗ Incorrect
In BST insertion, keys less than root go to left, greater keys go to right.
5fill in blank
hardFill all three blanks to complete the main function that builds a BST and finds the kth smallest element.
DSA C
#include <stdio.h> #include <stdlib.h> int main() { struct Node* root = NULL; root = insert(root, 20); root = insert(root, 8); root = insert(root, 22); root = insert(root, 4); root = insert(root, 12); int k = [1]; int result = kthSmallest(root, [2]); printf("%s %d\n", "Kth smallest element is", [3]); return 0; }
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a wrong variable to kthSmallest.
Printing k instead of the result.
✗ Incorrect
Set k=3, pass k to kthSmallest, and print the result variable.
