Binary Search Tree - Deletion (C++)
suggest changeEach node in a BST has at most two children (a left child and a right child). Every key in a node's left subtree is less than or equal to the node's key. Every key in its right subtree is greater than the node's key.
Deleting a node in a tree while maintaining its Binary search tree property.
There are three cases to be considered while deleting a node.
- Case 1: Node to be deleted is the leaf node.(Node with value 22).
- Case 2: Node to be deleted has one child.(Node with value 26).
- Case 3: Node to be deleted has both children.(Node with value 49).
Explanation of cases:
- When the node to be deleted is a leaf node then simply delete the node and pass
nullptrto its parent node. - When a node to be deleted is having only one child then copy the child value to the node value and delete the child (Converted to case 1)
- When the node to be deleted has two children, copy the minimum key from its right subtree into the node, then delete that minimum from the right subtree (converted to case 2).
Note: The minimum in the right sub tree can have a maximum of one child and that too right child if it’s having the left child that means it’s not the minimum value or it’s not following BST property.
The structure of a node in a tree and the code for Deletion:
struct node
{
int data;
node *left, *right;
};
node* delete_node(node *root, int data)
{
if(root == nullptr) return root;
else if(data < root->data) root->left = delete_node(root->left, data);
else if(data > root->data) root->right = delete_node(root->right, data);
else
{
if(root->left == nullptr && root->right == nullptr) // Case 1
{
free(root);
root = nullptr;
}
else if(root->left == nullptr) // Case 2
{
node* temp = root;
root= root->right;
free(temp);
}
else if(root->right == nullptr) // Case 2
{
node* temp = root;
root = root->left;
free(temp);
}
else // Case 3
{
node* successor = root->right;
node* parent = root;
while (successor->left != nullptr)
{
parent = successor;
successor = successor->left;
}
root->data = successor->data;
if (parent == root) parent->right = successor->right;
else parent->left = successor->right;
free(successor);
}
}
return root;
}
Time complexity of above code is O(h), where h is the height of the tree.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents