/* * Balance the tree. Start balancing from the given node. */ void AVL_tree::balance(AVL_tree::Node *node) { Node *tmp = NULL; int diff = 0, diff2 = 0;; while (node != NULL) { diff = balance_index(node); if (diff == 2) { tmp = node->left_child; diff2 = balance_index(tmp); // Double rotation situation. if (diff2 == -1) { rotate_left(tmp->right_child); } rotate_right(node->left_child); // node->parent is a new root of the subtree. // Update heights to the root. update_heights(node->parent); break; } else if (diff == -2) { tmp = node->right_child; diff2 = balance_index(tmp); // Double rotation situation. if (diff2 == 1) { rotate_right(tmp->left_child); } rotate_left(node->right_child); // node->parent is a new root of the subtree. // Update heights to the root. update_heights(node->parent); break; } // If subtree is balanced, just update node's height. // Check parent subtree. node->height = 1 + std::max(height(node->left_child), height(node->right_child)); node = node->parent; } }
int insert(AVL **r,int data) { /*AVL *ptr; AVL *parent; ptr=parent=*r;*/ AVL *nNode=createAvlNode(data); if(!nNode) return 0; else if(*r==NULL) { *r=nNode; return 1; } if(data < (*r)->value) { insert(&((*r)->left),data); cal_height(*r); //printf("value : %d hieght : %d",(*r)->value,(*r)->height); if(diff_height(*r)==2) { if(data < (*r)->left->value) //LL IMBALANCE RightRo(r); else //LR IMBALANCE { LeftRo(&((*r)->left)); RightRo(r); } } update_heights(*r); } if(data > (*r)->value) { insert(&((*r)->right),data); cal_height(*r); //printf("value : %d hieght : %d",(*r)->value,(*r)->height); if(diff_height(*r)==2) { if(data < (*r)->right->value) //RR IMBALANCE LeftRo(r); else //LR IMBALANCE { RightRo(&((*r)->right)); LeftRo(r); } } update_heights(*r); } }