In this article, we will discuss deleting a node from a given binary search tree. Before we delete a node, we have to know what kind of node is it. A BST can have three types of nodes:

caption

  1. Node with no child, i.e., leaf node. We simply remove this kind of node from the tree—for example, 20.
  2. caption

  3. Node with one child: We replace this node with its child node (left or right). For example, 50
  4. caption

  5. Node with two children: We replace its contents with a minimum value in its right subtree or maximum value in its left subtree for this kind of node. And delete that minVal/maxVal node.

This can also be rephrased as replacing the contents of the node to be deleted with the inorder successor (node that comes just after the node to be deleted in the inorder traversal), which will be the minimum value in the right subtree or replacing contents of the node to be deleted with the inorder predecessor (node that comes just before the node to be deleted in the inorder traversal) which will be the maximum value in the left subtree — and deleting the inorder successor/predecessor node after; for example, 100.

caption

CODE:

  1. #include
  2. using namespace std;
  3. class TreeNode{
  4. public:
  5. int val;
  6. TreeNode *left, *right;
  7. TreeNode(int data){
  8. val = data;
  9. left = right = NULL;
  10. }
  11. };
  12. void inorder(TreeNode* root){
  13. if(!root) return;
  14. inorder(root->left);
  15. coutleft = insert(root->left, val);
  16. else
  17. root->right = insert(root->right, val);
  18. return root;
  19. }
  20. TreeNode* minValueNode(TreeNode* root){
  21. TreeNode* temp = root;
  22. while(temp->left)
  23. temp = temp->left;
  24. return temp;
  25. }
  26. TreeNode* deleteTreeNode(TreeNode* root, int val){
  27. if (root == NULL)
  28. return root;
  29. if (val < root->val)
  30. root->left = deleteTreeNode(root->left, val);
  31. else if (val > root->val)
  32. root->right = deleteTreeNode(root->right, val);
  33. else {
  34. if (root->left == NULL && root->right == NULL)
  35. return NULL;
  36. else if (root->left == NULL) {
  37. TreeNode* temp = root->right;
  38. free(root);
  39. return temp;
  40. }
  41. else if (root->right == NULL) {
  42. TreeNode* temp = root->left;
  43. free(root);
  44. return temp;
  45. }
  46. TreeNode* temp = minValueNode(root->right);
  47. root->val = temp->val;
  48. root->right = deleteTreeNode(root->right, temp->val);
  49. }
  50. return root;
  51. }
  52. int main()
  53. {
  54. /* Let us create the following BST
  55. 100
  56. / \
  57. 50 150
  58. / \ / \
  59. 20 80 120 180 */
  60. TreeNode* root = NULL;
  61. root = insert(root, 100);
  62. root = insert(root, 50);
  63. root = insert(root, 150);
  64. root = insert(root, 20);
  65. root = insert(root, 80);
  66. root = insert(root, 120);
  67. root = insert(root, 180);
  68. cout