Question

I'm trying to understand the following piece of code for AVL trees, but am having some difficulty. I know that if the tree is left heavy, it will do a right rotation. Same goes if it's right heavy, it will do a left rotation. Appreciate if someone could explain or point me in the right direction in understanding the below code.

static void avl_rotate_right(TLDList *tld, TLDNode *node) {
    if (node->parent != NULL) {
        if (node->parent->left == node)
            node->parent->left = node->left;
        else
            node->parent->right = node->left;
    } else
        tld->root = node->left;

    node->left->parent = node->parent;
    node->parent = node->left;
    node->left = node->left->right;

    if (node->left != NULL)
        node->left->parent = node;
    node->parent->right = node;
}
Était-ce utile?

La solution

Basically this code is checking if node being rotated is the root. If that is the case then the root is reassigned to be left child of previous root. If node being rotated isn't the root the and the node being rotated is a left child it is replaced with its own left child, if it is a right child the parent nodes right child is replaced with the nodes left child.

Then the parent of the nodes left child is assigned to be the nodes parent. Then the nodes parent is assigned as the nodes left child. Then the left child of the node is assigned to be the right child of the nodes left child. If the nodes left child is not null the parent of the nodes left child is assigned to be the node if nodes left child is null the nodes parents right child is set to be node.

Helpful?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top