Advertisement
Guest User

Untitled

a guest
Dec 18th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.63 KB | None | 0 0
  1. BST* bst_get_smallest(BST* bst) {
  2.         while (bst != NULL && bst->left != NULL) {
  3.             bst = bst->left;
  4.         }
  5.     return bst;
  6. }
  7.  
  8.  
  9. BST* rec_bst_remove(BST **bst, int ele) {
  10.     BST* curNode = *bst;
  11.     BST* temp = curNode;
  12.  
  13.     if (ele < (*bst)->data) {
  14.         (*bst)->left = rec_bst_remove(&(*bst)->left, ele);
  15.  
  16.     } else if (ele > (*bst)->data) {
  17.         (*bst)->right = rec_bst_remove(&(*bst)->right, ele);
  18.  
  19.     } else {
  20.  
  21.         BST* dummy;
  22.  
  23.         //3 cases: 0 children, 1 child, 2 children
  24.         //case 0 children:
  25.  
  26.         if ((*bst)->left == NULL && (*bst)->right == NULL) {
  27.             bst_delete(&(*bst));
  28.             return 0;
  29.         }
  30.  
  31.             //case 1 child:
  32.  
  33.             // right child
  34.         else if ((*bst)-> left == NULL && (*bst)->right != NULL) {
  35.             dummy = *bst;
  36.             *bst = (*bst)->right;
  37.             free(dummy);
  38.             dummy = NULL;
  39.             return 0;
  40.  
  41.         }
  42.             // left child
  43.         else if ((*bst)-> left != NULL && (*bst)->right == NULL) {
  44.             dummy = *bst;
  45.             *bst = (*bst)->left;
  46.             free(dummy);
  47.             dummy = NULL;
  48.             return 0;
  49.  
  50.         } else {
  51.  
  52.             //case 2 children
  53.  
  54.             int dummyVal;
  55.             dummy = bst_get_smallest((*bst)->right);
  56.             dummyVal = dummy->data;
  57.             (*bst)->data = dummyVal;
  58.             bst_remove(&(*bst)->right, dummyVal);
  59.  
  60.  
  61.         }
  62.     }
  63.     return *bst;
  64. }
  65.  
  66.  
  67. int bst_remove (BST **bst, int ele) {
  68.  
  69.     if (!bst_contains(*bst, ele)) {
  70.         return -1;
  71.     }
  72.     rec_bst_remove(bst, ele);
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement