Rotation operation:
Since any one node has a maximum of two sons, it can only be caused by the following four cases when the height is unbalanced:
1. A single insertion of the left subtree of the left son of the node was made.
2. The right subtree of the left son of the node was inserted once.
3. An insert was made to the left subtree of the right son of the node.
4. An insert was made to the right subtree of the right son of the node.
After inserting a node into the AVL tree, you need to rebalance the AVL tree
Step1: From the insertion node to the root node, to observe whether there are unbalanced nodes (left and right subtree height difference),
if (not present), return
Else Step2
Step2: Mark unbalanced node as K1
if (k1.left.depth>k1.right.depth) step3;
else Step4;
Step3: Comparison of values based on insert values and K2 elements
if (k3<k2.element) Case 1;
else case 2;
Step4:if (k3<k2.element) Case 3;
else case 4;
Scenario 1:
K1 is an unbalanced node, K3 is an insertion node
After a single rotation, it becomes
Code implementation
Public avlnode<anytype> Rotatewithleftchild (avlnode<anytype> K1) {avlnode<anytype> K2 = K1.left; K1.left = K2.right; K2.right = k1;//Update height (omitted) return K2;}
Note: Be sure to update the parent node to the left of the subtree pointing
Case 4 is symmetric with Case 1, not repeating
Case 2: Corresponds to left and right double-spin
To describe clearly, even if the node in the tree is null, it is still marked as the letter Abcd
K1 for unbalanced nodes
Step1:k2
With K2 as the unbalanced node left-handed, the
Continue to K1 to the right of the unbalanced node to get the balance
Code:
Public avlnode<anytype> Doublewithleftchild (avlnode<anytype> K1) {k1.left = Rotatewithrightchild (K1.left ); return Rotatewithleftchild (K1);}
Case 3 symmetry with it
My collection frame third-play AVL tree