Complete the code to create a new BST node with the given value.
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = [1];
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}The new node's data field should be set to the given value parameter.
Complete the code to insert a value into the BST correctly.
struct Node* insert(struct Node* root, int value) {
if (root == NULL) {
return createNode([1]);
}
if (value < root->data) {
root->left = insert(root->left, value);
} else if (value > root->data) {
root->right = insert(root->right, value);
}
return root;
}When the root is NULL, we create a new node with the value to insert.
Fix the error in the code to find the minimum value node in a BST.
struct Node* findMinNode(struct Node* node) {
struct Node* current = node;
while (current->[1] != NULL) {
current = current->left;
}
return current;
}To find the minimum node, we keep going left until left child is NULL.
Fill both blanks to correctly delete a node with two children in BST.
struct Node* deleteNode(struct Node* root, int value) {
if (root == NULL) return root;
if (value < root->data) {
root->left = deleteNode(root->left, [1]);
} else if (value > root->data) {
root->right = deleteNode(root->right, [2]);
} else {
if (root->left == NULL) {
struct Node* temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
struct Node* temp = root->left;
free(root);
return temp;
}
struct Node* temp = findMinNode(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}We recursively delete the node with the given value in left or right subtree.
Fill all three blanks to complete the BST delete function handling all cases.
struct Node* deleteNode(struct Node* root, int value) {
if (root == NULL) return root;
if (value < root->data) {
root->left = deleteNode(root->left, [1]);
} else if (value > root->data) {
root->right = deleteNode(root->right, [2]);
} else {
if (root->left == NULL) {
struct Node* temp = root->right;
free(root);
return [3];
} else if (root->right == NULL) {
struct Node* temp = root->left;
free(root);
return temp;
}
struct Node* temp = findMinNode(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}The recursive calls use the value to delete, and when deleting a node with one child, return the child pointer.
