tree balancing - Understanding Balance Factors/Node Height for AVL rotations -
so having hard time understanding how balance avl trees. understand rotation stuff, can't figure out how find balance factor of node heights, example:
http://i.imgur.com/yh5znil.png
can explain me how find balance factor each node?
i know if height of [(left subtree) - (right subtree)] not within (-1<= x <= 1) unbalanced...but can't figure how find "x".
(edit: don't need code, want understand how find bf).
if understand question correctly, want know how maintain balance-factor of given node. best way keep track when doing "insert" in tree. because know whether new node going left or right side of "current" node. when goes left, decrement balance , when goes right, increment balance. idea have tree balanced before exit "insert" method.
another approach have seen not doing balancing during "insert". insert in bst. after insert, begin balancing act left subtree , right subtree height @ each node , start shuffling pointers. not approach since incur o(logn) every node in finding height , since every node, results n*o(logn).
i posting "insert" method once wrote keeps tree balanced @ every insert , not compute height separately @ point during insert. see if helps:
node* avl::insert(node* node, int key, int value) { if(node == null) node = new node(key, value); else if (key <= node->key) { node->balance--; node->left = insert(node->left, key, value); } else if (key > node->key) { node->balance++; node->right = insert(node->right, key, value); } // right tree heavy if (node->balance == 2) { // left tree unbalanced if (node->right && node->right->balance == 1) { // ll node = singleleftrotation(node); node->balance = 0; node->left->balance = 0; } if (node->right && node->right->balance == -1) { // lr int noderlbalance = node->right->left->balance; node = doubleleftrotation(node); node->balance = 0; node->left->balance = noderlbalance == 1 ? -1 : 0; node->right->balance = noderlbalance == -1 ? 1 : 0; } } // left tree heavy if (node->balance == -2) { // right tree unbalanced if (node->left && node->left->balance == -1) { // rr node = singlerightrotation(node); node->balance = 0; node->right->balance = 0; } if (node->left && node->left->balance == 1) { // rl int nodelrbalance = node->left->right->balance; node = doublerightrotation(node); node->balance = 0; node->left->balance = nodelrbalance == 1 ? -1 : 0; node->right->balance = nodelrbalance == -1 ? 1 : 0; } } return node; }
Comments
Post a Comment