Advertisement
i_love_rao_khushboo

Untitled

Sep 3rd, 2022
729
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. // A utility function to delete a given key in BST
  2. // NOTE THAT ROOT IS PASSED BY REFERENCE TO THE FUNCTION
  3. void BinarySearchTree::delete_(TreeNode* &root, int key) {
  4.     // base case
  5.     if(root == NULL) return;
  6.    
  7.     // if the given key is greater than the root node, recur for the right subtree
  8.     if(key > root->val) delete_(root->right, key);
  9.    
  10.     // if the given key is less than the root node, recur for the left subtree
  11.     else if(key < root->val) delete_(root->left, key);
  12.    
  13.     // key found
  14.     else {
  15.         // Case 1: node to be deleted has no children (it is a leaf node)
  16.         if(root->left == NULL and root->right == NULL) {
  17.             delete (root);
  18.             root = NULL;
  19.         }
  20.        
  21.         // Case 2: node to be deleted has two children
  22.         else if(root->left and root->right) {
  23.             // find its inorder predecessor node
  24.             TreeNode *pred = in_predecessor(root->left);
  25.            
  26.             // swap the values of the predecessor node & the current node
  27.             swap(root->val, pred->val);
  28.            
  29.             // recursively delete the predecessor. Note that the
  30.             // predecessor will have at most one child (left child)
  31.             delete_(root->left, key);
  32.         }
  33.        
  34.         // Case 3: node to be deleted has only one child
  35.         else {
  36.             // choose the child node
  37.             TreeNode *child = (root->left) ? root->left : root->right;
  38.             TreeNode *tmp = root;
  39.             root = child;
  40.            
  41.             delete (tmp);
  42.             tmp = NULL;
  43.         }
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement