| Home / Mainframe - DB2 / What is an AVL tree? |
What is an AVL tree? |
||||
AVL trees are self-adjusting, height-balanced binary search trees and are named after the inventors: Adelson-Velskii and Landis. A balanced binary search tree has O(log n) height and hence O(log n) worst case search and insertion times. However, ordinary binary search trees have a bad worst case. When sorted data is inserted, the binary search tree is very unbalanced, essentially more of a linear list, with O(n) height and thus O(n) worst case insertion and lookup times. AVL trees overcome this problem. An AVL tree is a binary search tree in which every node is height balanced, that is, the difference in the heights of its two subtrees is at most 1. The balance factor of a node is the height of its right subtree minus the height of its left subtree (right minus left!). An equivalent definition, then, for an AVL tree is that it is a binary search tree in which each node has a balance factor of -1, 0, or +1. Note that a balance factor of -1 means that the subtree is left-heavy, and a balance factor of +1 means that the subtree is right-heavy. Each node is associated with a Balancing factor.
Here is some recursive C code that sets the Balance factor for all nodes starting from the root....
count = 1; if(p == NULL) if(templ < tempr) // Set the nodes balancing factor. return(count);
0 (par) 0 0 (p) 0 0 (tmp) 0 0 0 0
Here we left rotate the tree around node p
tmp = p->right; if(par) // Reclaculate the balance factors
0 0 0 0 0 0 0 0
0 (par) 0 0 (p) 0 (tmp) 0 0 0 0 0
Here we right rotate the tree around node p
if(par) // Recalculate the balancing factors...
0 (par) 0 0 (tmp) 0 0 0 0 0 0
|
||||
