0
struct node *delete(struct node *root, int key)
{  

    struct node *remove_node;
    if (root == NULL){
        return root;
    }

    if ( key < root->key) {
        root->left = delete(root->left, key);

    } else if ( key > root->key) {
        root->right = delete(root->right,key);

    } else {

        if ((root->left == NULL) && (root->right != NULL)){
            remove_node = root->right;
            *root = *remove_node;
            deletetree(remove_node); // this is for free-ing the memory

        } else if ((root->right == NULL)  && (root->left != NULL)){
            remove_node = root->left;
            *root = *remove_node;
            deletetree(remove_node);

        } else if ((root->right == NULL)  && (root->left == NULL)){
            remove_node = root;
            root = NULL;

        } else {

            remove_node = successor(root);
            root->key = remove_node->key;
            root->right = delete(root->right, remove_node->key);
        }
    }

    if (root == NULL) {
        return root;

    if (balance_factor(root) == 2){
        if (balance_factor(root->left) == -1) {
            return single_right_rotation(root);

        } else if (balance_factor(root->left) == 1) {
            return double_left_rotation(root);
        }
    }

    if (balance_factor(root) == -2) {
        if (balance_factor(root->right) == -1) {
            return single_left_rotation(root);
        }
        else if (balance_factor(root->right) == 1)  { 
        return double_right_rotation(root);
            }
        }
    }

    return root;    
}

Here's my code for deleting an element in an AVL tree. Everything seems to work fine, it handles all the case when node n has no children, one children and two children. But for some odd reason it does not balance the tree nor does it reaches that block of code.

Hopefully someone can help me debug the code cause I cannot find where "exactly" the error is coming from.

Thanks in Advance

PS: the successor function just returns the minimum element on the right tree of the node to be deleted and the deletetree deals with free-ing memory allocation stuffs. Also i am 100% that my rotations work because it worked perfectly in my insert function.

Anthony
  • 12,177
  • 9
  • 69
  • 105
ms. sakura
  • 201
  • 1
  • 4
  • 11
  • possible duplicate of [AVL delete algorithm in C](http://stackoverflow.com/questions/10988410/avl-delete-algorithm-in-c) –  Jun 11 '12 at 23:57

1 Answers1

0

You can use temp root, as reference and you can change like this:

struct node *localRoot = root;

And you change roots to localRoot, probably the problem is solved. I hope it is helpfull.

Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
Ramazan
  • 37
  • 1