Complete the code to insert a new node into a Binary Search Tree (BST).
struct Node* insert(struct Node* root, int key) {
if (root == NULL) {
root = (struct Node*)malloc(sizeof(struct Node));
root->key = key;
root->left = root->right = NULL;
return root;
}
if (key [1] root->key) {
root->left = insert(root->left, key);
} else if (key > root->key) {
root->right = insert(root->right, key);
}
return root;
}In a BST, keys less than the current node go to the left subtree, so we use < to decide where to insert.
Complete the code to check if a key exists in a hash map using chaining.
int contains(struct HashMap* map, int key) {
int index = key % map->capacity;
struct Node* current = map->buckets[index];
while (current != NULL) {
if (current->key [1] key) {
return 1;
}
current = current->next;
}
return 0;
}To find a key in a hash map bucket, we check if the current node's key equals the searched key.
Fix the error in the BST search function to correctly find a key.
struct Node* search(struct Node* root, int key) {
if (root == NULL || root->key [1] key) {
return root;
}
if (key < root->key) {
return search(root->left, key);
} else {
return search(root->right, key);
}
}The base case returns the node if its key equals the searched key, so use ==.
Fill both blanks to create a hash map insertion that handles collisions by chaining.
void insert(struct HashMap* map, int key) {
int index = key [1] map->capacity;
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->key = key;
newNode->next = map->buckets[[2]];
map->buckets[index] = newNode;
}Use modulo (%) to find the bucket index, then insert the new node at the head of that bucket's linked list.
Fill all three blanks to create a function that prints BST keys in ascending order.
void inorder(struct Node* root) {
if (root == NULL) return;
inorder(root->[1]);
printf("%d ", root->[2]);
inorder(root->[3]);
}Inorder traversal visits left subtree, then current node's key, then right subtree to print keys in ascending order.
