Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- BST* bst_get_smallest(BST* bst) {
- while (bst != NULL && bst->left != NULL) {
- bst = bst->left;
- }
- return bst;
- }
- BST* rec_bst_remove(BST **bst, int ele) {
- BST* curNode = *bst;
- BST* temp = curNode;
- if (ele < (*bst)->data) {
- (*bst)->left = rec_bst_remove(&(*bst)->left, ele);
- } else if (ele > (*bst)->data) {
- (*bst)->right = rec_bst_remove(&(*bst)->right, ele);
- } else {
- BST* dummy;
- //3 cases: 0 children, 1 child, 2 children
- //case 0 children:
- if ((*bst)->left == NULL && (*bst)->right == NULL) {
- bst_delete(&(*bst));
- return 0;
- }
- //case 1 child:
- // right child
- else if ((*bst)-> left == NULL && (*bst)->right != NULL) {
- dummy = *bst;
- *bst = (*bst)->right;
- free(dummy);
- dummy = NULL;
- return 0;
- }
- // left child
- else if ((*bst)-> left != NULL && (*bst)->right == NULL) {
- dummy = *bst;
- *bst = (*bst)->left;
- free(dummy);
- dummy = NULL;
- return 0;
- } else {
- //case 2 children
- int dummyVal;
- dummy = bst_get_smallest((*bst)->right);
- dummyVal = dummy->data;
- (*bst)->data = dummyVal;
- bst_remove(&(*bst)->right, dummyVal);
- }
- }
- return *bst;
- }
- int bst_remove (BST **bst, int ele) {
- if (!bst_contains(*bst, ele)) {
- return -1;
- }
- rec_bst_remove(bst, ele);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement