Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
Input: root = [5,3,6,2,4,null,7], key = 3
Output: [5,4,6,2,null,null,7]
Explanation: Given key to delete is 3. So we find the node with value 3 and delete it.
One valid answer is [5,4,6,2,null,null,7], shown in the above BST.
Please notice that another valid answer is [5,2,6,null,4,null,7] and it’s also accepted.
Input: root = [5,3,6,2,4,null,7], key = 0
Output: [5,3,6,2,4,null,7]
Explanation: The tree does not contain a node with value = 0.
Input: root = [], key = 0
Output: []
From: LeetCode
Link: 450. Delete Node in a BST
1. Base Case Check: If the root is NULL, there’s nothing to delete, and the function returns NULL.
2. Recursive Search:
3. Node Deletion: Once the node to be deleted (root) is found (i.e., root->val is equal to key), there are three scenarios to handle:
4. Returning the New Tree: The function returns the updated root pointer, which points to the BST after the deletion operation is completed.
struct TreeNode* findMin(struct TreeNode* node) {
while (node->left != NULL) node = node->left;
return node;
}
struct TreeNode* deleteNode(struct TreeNode* root, int key) {
if (root == NULL) return root; // Base case: the tree is empty
// Recursive calls for the children of the node
if (key < root->val) { // The key to be deleted is in the left subtree
root->left = deleteNode(root->left, key);
} else if (key > root->val) { // The key to be deleted is in the right subtree
root->right = deleteNode(root->right, key);
} else { // The node to be deleted has been found
// Case 1: The node has no child or only one child
if (root->left == NULL) {
struct TreeNode* temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
struct TreeNode* temp = root->left;
free(root);
return temp;
}
// Case 2: The node has two children
struct TreeNode* temp = findMin(root->right); // Find the in-order successor
// Copy the in-order successor's content to this node
root->val = temp->val;
// Delete the in-order successor
root->right = deleteNode(root->right, temp->val);
}
return root; // Return the (possibly updated) root pointer
}