Skip to content

Instantly share code, notes, and snippets.

@nerohoop
Created January 8, 2018 01:59
Show Gist options
  • Save nerohoop/9b3eb3be59c88e93a92f1a8753ef94ea to your computer and use it in GitHub Desktop.
Save nerohoop/9b3eb3be59c88e93a92f1a8753ef94ea to your computer and use it in GitHub Desktop.
Node* BinarySearchTree::deleteKey(Node *root, int key) {
if (!root) return root;
if (key < root->val) {
// If the key to be deleted is smaller than the root's key, then it lies in left subtree
root->left = deleteKey(root->left, key);
} else if (key > root->val) {
// If the key to be deleted is greater than the root's key, then it lies in right subtree
root->right = deleteKey(root->right, key);
} else {
// Node with only one child or no child
if (!root->left) {
Node *temp = root->right;
free(root);
return temp;
} else if (!root->right) {
Node *temp = root->left;
free(root);
return temp;
}
// Node with two children: get the inorder successor
Node *temp = minNode(root->right);
// Copy the inorder successor's content to this node
root->val = temp->val;
// Delete the inorder successor
root->right = deleteKey(root->right, temp->val);
}
return root;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment