Objective
Everyone has played the ball big battle game, his prototype is Agar.io, in this game we play a small ball, just born we in addition to speed, vision survival ability are general, in order to pursue some kind of balance, through constantly devour other small ball to let oneself grow, grow longer, But our speed is falling. This process of chasing balance, is our topic today, AVL tree, AVL Tree also known as the binary balance tree, is a binary sorting tree, where each node's Saozi right subtree height difference is at most equal to 1. The advantage of doing this is that our search will be very convenient, It also avoids the performance effects of turning the two-fork tree into a diagonal tree.
Realization principle of binary balance tree
In the AVL tree, whenever we insert a node, we check to see if it breaks the balance of the tree because of the insertion, and if we break the balance, we can find the smallest unbalanced tree (the subtree of the node closest to the insertion node, which is the root of the nodes with a balance factor greater than 1), and rotate it while maintaining the AVL tree characteristics To achieve a balance. So what are the 4 broken-balance insertions?
Insert left subtree of node left subtree LL
Insert the right subtree of the left subtree of the node LR
Insert the left subtree of the right subtree of the node RL
Right subtree RR of the right subtree of the insertion node
So for these four cases, we need to use these rotating operations, such as LL to use
ll rotate public static node Rotatewidthleftchild (node tree) {node root=tree.leftchild;tree.leftchild=root.rightchild; Root.rightchild=tree;tree.height=math.max (height (tree.leftchild), height (tree.rightchild)) +1;root.height= Math.max (height (root.leftchild), tree.height) +1;return root;}
LR to use
Lrpublic static node Doublewidthleftchild (node tree) {Tree.leftchild=rotatewidthrightchild (tree.leftchild); return Rotatewidthleftchild (tree);}
RR to use
RR rotates public static node Rotatewidthrightchild (node tree) {node root=tree.rightchild;tree.rightchild=root.leftchild; Root.leftchild=tree;tree.height=math.max (height (tree.leftchild), height (tree.rightchild)) +1;root.height= Math.max (height (root.leftchild), tree.height) +1;return root;}
RL to use
Rlpublic static node Doublewidthrightchild (node tree) {Tree.rightchild=rotatewidthleftchild (tree.rightchild); return Rotatewidthrightchild (tree);}
Data Structure AVL tree