Deleting a node from a Binary Search Tree
Deleting a node from a Binary Search Tree
The left child of a node contains values less than the node.
The right child of a node contains values than the node.
1. Start at the root: If the tree is empty, the new node becomes the root.
2. Recursively search the tree:
o If the value to be inserted is less than the current node, move to the
left child.
o If the value to be inserted is greater than the current node, move to
the right child.
3. Insert the new node: When a NULL (empty) child is found, place the new
node there.
struct Node {
int key;
Node* left;
Node* right;
Node(int k){
key = k;
};
curr = curr->left;
return curr;
// Base case
if (root == nullptr)
return root;
if (root->key > x)
else {
// Cases when root has 0 children
if (root->left == nullptr) {
delete root;
return temp;
if (root->right == nullptr) {
delete root;
return temp;
root->key = succ->key;
return root;
}
// Utility function to do inorder
// traversal(sorted)
if (root != nullptr) {
inorder(root->left);
inorder(root->right);
int main(){
int x = 15;
inorder(root);
return 0;
}
Output: 5 10 12 18.
Time Complexity:
Space Complexity: