The AVL tree is a highly balanced two-fork tree, with a height difference of two subtrees of any node <=1
Implementing the AVL Tree
Defines an AVL tree,avltree, that defines Avltree 's intra-node class Avlnode, The node contains the following attributes:
1.key-- keywords to sort the nodes of the AVL Tree
2.left--left dial hand tree
3.right--Right sub-tree
4.height--Height
If you insert a node in the AVL tree, it may cause the AVL tree to lose its balance in four different states:
LL: Zo,leftleft
LR: Around,leftright
RL: Right-left,rightleft
RR: Right, right,RightRight
Solve the above situation
Solve LL, need left single rotation
Resolve RR, need right single rotation
To resolve LR, you need to first right single rotation, then left single rotation
To solve RL, you need to turn the left single rotation, then the right single rotation
Achieve left single rotation
K1,K2
K2 left to K1 .
K1 right to the left of K2
K2 to K1 right .
Achieve right single rotation
K1,K2
K1 right to K2 .
K2 left to K1 right .
K1 to K2 's left.
The height of the node is its left subtree or right subtree, and the height of the tall one adds 1 .
/*** AVL Tree Test *@authorTaoshihan *@param<T> **/ Public classAvltree<textendsComparable<t>> { PrivateAvlnode Mroot;//root node classAvlnode<textendsComparable<t>>{ PrivateT key;//Key Value Private intHeight//Height PrivateAvlnode left;//left dial hand tree PrivateAvlnode right;//Right sub-tree PublicAvlnode (T key,avlnode Left,avlnode right) { This. key=key; This. left=Left ; This. right=Right ; This. height=0; } } /*** Get node Height *@paramTree *@return */ Public intHeight (avlnode<t>tree) { if(tree!=NULL){ returnTree.height; } return0; } /*** Take out the tall one in the left and right subtree *@paramA *@paramb *@return */ Public intMaxHeight (intAintb) { returnA>b?a:b; } /*** Left single rotation *@paramK2 *@return */ PublicAvlnode<t> Leftleftrotation (avlnode<t>K2) {Avlnode K1; K1=K2.left; K2.left=K1.right; K1.right=K2; K2.height=maxheight (height (k2.left), height (k2.right)); K1.height=maxheight (height (k1.left), height (k1.right)); returnK1; } /*** Right Single rotation *@paramK2 *@return */ PublicAvlnode<t> Rightrightrotation (avlnode<t>K1) {Avlnode K2; K2=K1.right; K1.right=K2.left; K2.left=K1; K2.height=maxheight (height (k2.left), height (k2.right)); K1.height=maxheight (height (k1.left), height (k1.right)); returnK2; }
[Javase] Data structure (basic concept of AVL tree)