AVL tree in order to prevent the depth of the tree to avoid a data structure, on the basis of a binary tree added a rule: the left child of each node and the right subtree of the height of the maximum difference of 1.
One of the difficulties is: insert a node. Deleting a node is more difficult, and the lazy Delete method is used here. Where, at the time of insertion, update all the heights of those nodes on the root node path.
AVL node:
struct avlnode{ ElementType Element; Avltree left; Avltree right; int Height;};
Question one: How to know which node is out of balance when inserting a node
When inserting a node, the new tree can be modified to satisfy the characteristics----rotation of the AVL tree by making a simple correction to the tree.
The node that needs to be balanced is called a. Since any node has a maximum of two nodes, the height difference between the two subtrees trees at point A is 2. It can be guessed that this imbalance may occur in the following four cases:
- An insertion of the left subtree of A's left son
- Insert the right sub-tree of A's left son
- Insert a right son of a right child tree
- Insert the left sub-tree of the right son of a
Where case 1 and 3,2 and 4 are about the A-point mirroring symmetry, which can be seen in the code. Where adjustments of 1 and 3 are performed on a single rotation, 2 and 4 require a double rotation.
1. When an insert is made to the left subtree of A's left son, an imbalance occurs:
The rotation code is:
Static Position singlerotatewithleft (Position K2) { Position K1; = K2-> left; K2->left = k1-> right; K1->right = K2; K21; K11; return K1;}
2. The right sub-tree of the left son of a is inserted into a node, and an imbalance occurs:
The rotation code is:
Static Position doublerotatewithleft (Position K3) { K3->left = Singlerotatewithright (k3-> left); return Singlerotatewithleft (K3);}
The rotation codes for 3 and 4 are:
StaticPosition singlerotatewithright (Position K2) {Position K1; K1= k2->Right ; K2->right = k1->Left ; K1->left =K2; K2->height = Max (height (k2->left), height (k2->right)) +1; K1->height = Max (K2->height, Height (k1->right)) +1; returnK1;}StaticPosition doublerotatewithright (Position K3) {K3->right = Singlerotatewithleft (k3->Right ); returnsinglerotatewithright (K3);}
Individual projects: implementation of the AVL tree for data structure