Binary Search Tree(BST)- Deletion Algorithm
Binary Search Tree(BST)- Deletion Algorithm
Algorithm:
deleteNode(root, val)
Input: Root of the tree and value of the node to be deleted
Output: address of root node
1. if(root == NULL)
2. return NULL
3. if(root->key < val)
4. root->right = deleteNode(root->right,val)
5. else if(root->key > val)
6. root->left = deleteNode(root->left,val)
7. else
8. if(root->left == NULL && root->right == NULL)
9. free(root)
10. return NULL
11. else if(root->left == NULL)
12. temp = root->right;
13. free(root)
14. return temp
15. else if(root->right == NULL)
16. temp = root->left
17. free(root)
18. return temp
19. else
20. rightMin = find_InorderSuccessor(root->right)
21. root->key = rightMin
22. root->right = deleteNode(root->right,rightMin)
23. return root; //return the actual root's address
Algorithm:
1. Starting at the root, find the deepest and rightmost node in the binary tree and the node
which we want to delete.
2. Replace the deepest rightmost node’s data with the node to be deleted.
3. Then delete the deepest rightmost node.