Course Design-AVL search tree Theoretical Basis

Source: Internet
Author: User

From: http://www.nctvu.cn/kejian/sjjg/7.6.htm

Http://www.nctvu.cn/kejian/sjjg/7.6.htm7.6 AVL Tree

7.6.1 AVL Tree Definition

Highly balanced binary search tree

An AVL Tree, an empty tree, or a binary search tree with the following properties: Its left and right subtree are both AVL trees, the absolute value of the height difference between the left subtree and the right subtree cannot exceed 1.

Highly balanced binary search tree

Balance factor)

1. Each node is appended with a number, indicating the height difference between the height of the right subtree of the node and the height of the Left subtree. This number is the balance factor of the node.

2. According to the AVL Tree definition, the equilibrium factors of any node can only be-and 1.

3. If the absolute value of the balancing factor at a node is greater than 1, the binary search tree will lose its balance and will no longer be AVL.

4. If a binary search tree is highly balanced, it becomes an AVL Tree. If it has n nodes, its height can be maintained at O (log2n), and the average search length can also be maintained at O (log2n ).

AVL tree class definition

Template <class type> class avltree {
Public:
Struct avlnode {
Type data;
Avlnode * left, * right;
Int balance;
Avlnode (): Left (null), right (null), balance (0 ){}
Avlnode (type D, avlnode * l = NULL, avlnode * r = NULL)
: Data (D), left (L), right (R), balance (0 ){}
};
Protected:
Type refvalue;
Avlnode * root;
Int insert (avlnode * & tree, Type X,
Int & taller );
Void rotateleft (avlnode * tree, avlnode * & newtree );

Void rotateright (avlnode * tree, avlnode * & newtree );

Void leftbalance (avlnode * & tree,
Int & taller );
Void rightbalance (avlnode * & tree,
Int & taller );
Int depth (avlnode * t)
Const;
Public:
Avltree (): Root (null ){}
Avlnode (type ref): refvalue (REF), root (null ){}
Int insert (Type X ){
Int taller;
Return insert (root, X, Taller );
}
Friend istream & operator> (istream & in, avltree <type> & tree );
Friend ostream & operator <(ostream & out, const avltree <type> & tree );
Int depth () const;
}

7.6.2 balanced rotation

1. If a new node is inserted in a balanced binary search tree, an imbalance occurs.
In this case, you must adjust the structure of the tree to make it balanced.

2. There are two types of balanced rotation:

Single rotation (left and right rotation) and double rotation (left and right rotation)

3. When a new node is inserted, the balance of the related nodes in the AVL Tree changes. Therefore, after inserting a new node, You need to trace back from the insertion position along the path to the root to check the balance factor of each node (height difference between left and right subtree ).

4. If a height imbalance is found at a node, stop backtracking.

5. From the point where an imbalance occurs, take the two layers of nodes directly along the Backtracking path.

6. If the three nodes are in a straight line, they are balanced by single rotation. Single rotation can be divided into left single rotation and right single rotation by its direction. One of them is another image, and its direction is related to the unbalanced shape.

7. If the three nodes are on a broken line, the dual rotation is used for balancing. Double rotation is divided into two types: First left, right, first right, and then left.

Right single rotation Left Single Rotation Rotate both sides Right-left Rotation

1. rotateleft)

(1) If a new node is inserted in subtree E, the height of the subtree increases by 1, resulting in the balance factor of node A becoming + 2, resulting in imbalance.

(2) Check the three nodes A, C, and E along the insert path. They are in a straight line in the direction of "/" and must be rotated on the left.

(3) Use node C as the rotation axis to rotate node A against the clockwise side.

Left Single Rotation Algorithm

Template <class type>
Void avltree <type >:: rotateleft (avlnode * tree, avlnode * & newtree ){

Newtree = tree → right;

Tree → right = newtree → left;

Newtree → left = tree;

}

2. Right single rotation (rotateright)

(1) Insert a new node on the left subtree d to increase its height by 1, resulting in the increase of the balance factor of node a to-2, resulting in an imbalance.

(2) To restore the tree to a balance, take three consecutive nodes A, B, and D from a along the insert path. They are in a straight line in the direction, right single rotation is required.

(3) rotate node a clockwise with Node B as the rotating axis.

Algorithm for right single rotation

Template <class type>
Void avltree <type >:: rotateright (avlnode * tree, avlnode * & newtree ){

Newtree = tree → left;

Tree → left = newtree → right;

Newtree → right = tree;

}

3. rotationleftright)

(1) Insert a new node into the subtree f or g, and the height of the subtree increases by 1. The equilibrium factor of node A is changed to-2, and an imbalance occurs.

(2) select three nodes A, B, and E from node A along the insert path. They are located in a bar like "?" Line, so you need to first left and right double rotation.

(3) First, Take node e as the rotation axis, rotate Node B against the clockwise side, and use the e-generation to replace the original position B for the left single rotation.

(4) Take node e as the rotation axis, and rotate node a clockwise to make the right single rotation. Balance it.

Left-balanced algorithm

Template <class type>
Void avltree <type >:: leftbalance (avlnode * & tree,
Int & taller ){

Avlnode * leftsub = tree → left, * rightsub;

Switch (leftsub → balance ){

Case-1:

Tree → balance = leftsub → balance = 0;

Rotateright (Tree, tree );

Taller = 0;

Break;

Case 0:

Cout <"the tree has been balanced./N ";

Break;

Case 1:

Rightsub = leftsub → right;

Switch (rightsub → balance ){

Case-1:

Tree → balance = 1;

Leftsub → balance = 0;

Break;

Case 0:

Tree → balance = leftsub → balance = 0;

Break;

Case 1:

Tree → balance = 0;

Leftsub → balance =-1;

Break;

}

Rightsub → balance = 0;

Rotateleft (leftsub, tree → left );

Rotateright (Tree, tree );

Taller = 0;

}

}

4. rotationrightleft)

(1) The right-left double rotation is an image of the left-right double rotation.

(2) Insert a new node into the subtree f or g, and the height of the subtree increases by 1. The equilibrium factor of node A is changed to 2, and an imbalance occurs.

(3) select three nodes A, C, and D from node A along the insert path. They are located in a bar like "?" Line, You need to first right and then left double rotation.

(4) First, perform the right single rotation: Take node D as the rotation axis, rotate node c clockwise, and replace the original C position with D.

(5) perform the left single rotation: use node D as the rotation axis, and rotate node A against the clockwise side to restore the tree balance.

Right Balancing Algorithm

Template <class type>
Void avltree <type >:: rightbalance (avlnode * & tree,
Int & taller ){

Avlnode * rightsub = tree → right, * leftsub;

Switch (rightsub → balance ){

Case 1:

Tree → balance = rightsub → balance = 0;

Rotateleft (Tree, tree );

Taller = 0;

Break;

Case 0:

Cout <"the tree has been balanced./N ";

Break;

Case-1:

Leftsub = rightsub → left;

Switch (leftsub → balance ){

Case 1:

Tree → balance =-1;

Rightsub → balance = 0;

Break;

Case 0:

Tree → balance = rightsub → balance = 0;

Break;

Case-1:

Tree → balance = 0;

Rightsub → balance = 1;

Break;

}

Leftsub → balance = 0;

Rotateright (rightsub, tree → left );

Rotateleft (Tree, tree );

Taller = 0;

}

}

 

7.6.3 insert and delete AVL trees

AVL Tree insertion:

1. When a new node is inserted into an AVL tree that is originally highly balanced, such as the absolute value of the balance factor of a node in the fruit tree | balance |> 1, an imbalance occurs, balance processing is required.

2. On the AVL Tree, heavy-load operations ">" and "<" are defined, as well as the algorithm for central order traversal. These operations can be used to establish the AVL Tree and output the node data.

3. Algorithms start from an empty tree and gradually build an AVL Tree by inputting a series of key codes of objects. When a new node is inserted, the algorithm previously given is used for balanced rotation.

For example, the input key code sequence is {16, 3, 7, 11, 9, 26, 18, 14, 15}. The insertion and adjustment process is as follows.

Process of building from the empty tree

1. The following algorithm uses recursion to insert a new node as a leaf node and modify the balance factor of each node layer by layer.

2. When an imbalance is detected, immediately perform a balanced rotation operation to rebalance the nodes in the tree.

3. In the program, use the variable success to record whether the new node is successfully stored and allocated, and use it as the return value of the function.

4. The algorithm starts from the root node of the tree and recursively locates the insertion position. After finding the insertion position (NULL pointer), dynamically allocate storage space for the new node, insert it as the leaf node, and set success to 1, and then set taller to 1, to indicate that the insert is successful. Make necessary adjustments when exit recursion along the insert path and return up.

Template <class type>
Int avltree <type >:: insert (avlnode * & tree, Type X,
Int & taller ){

Int success;

If (tree = NULL ){

Tree = new avlnode (X );

Success = tree! = NULL? 1: 0;

If (SUCCESS) taller = 1;

}

Else if (x <tree → data ){

Success = insert (tree → left, X, Taller );

If (Taller)

Switch (tree → balance ){

Case-1:

Leftbalance (tree, Taller );

Break;

Case 0:

Tree → balance =-1;

Break;

Case 1:

Tree → balance = 0;

Taller = 0;

Break;

}

}

Else {

Success = insert (tree → right, X, Taller );

If (Taller)

Switch (tree → balance ){

Case-1:

Tree → balance = 0;

Taller = 0;

Break;

Case 0:

Tree → balance = 1;

Break;

Case 1:

Rightbalance (tree, Taller );

Break;

}

}

Return success;

}

AVL Tree heavy load operations>, <and traversal algorithm implementation:

Template <class type> istream & operator> (istream & in, avltree <type> & tree ){
Type item;
Cout <"constructing AVL Tree:/N ";
Cout <"input data (ended with" <tree. refvalue <):";

In> item;
While (item! = Tree. refvalue ){
Tree. insert (item );
Cout <"input data (ended with" <tree. refvalue <):";
In> item;
}
Return in;
}

Template <class type>
Void avltree type
: Traverse (avlnode * PTR, ostream & out) const {
// Traverse and output data in the AVL Tree in ascending order
If (PTR! = NULL ){
Traverse (PTR → left, out );
Out <PTR → data <'';
Traverse (PTR → right, out );
}
}

Template <class type> ostream & operator <(ostream & out,
Const avltree <type> & tree ){
Out <"AVL Tree's central order traversal./N ";
Tree. Traverse (tree. Root, out );
Out <Endl;
Return out;
}

AVL tree deletion

1. If the deleted node X has at most one child, the problem is relatively simple. If the deleted node X has two children, first search for X's direct precursor Y in the central order (you can also find the direct successor ). Transfer the content of node y to node X. Now the problem is to delete node y. Use node y as the deleted node X.

2. delete node X from the tree. Because node X has at most one child, we can simply point the pointer pointing to X in the parent node of X to this child node. If node X has no child, x The corresponding pointer of the parent node is set to null. Then, the height of the subtree that uses node X as the root is reduced by 1,

3. The change of height must be traced back along the path X to the root path to influence each node on the Path.

4. Use a Boolean variable shorter to specify whether the height of the subtree is shortened. The operations to be performed on each node depend on the shorter value and the balance of the node, and sometimes depend on the children's balance.

5. The shorter value of the Boolean variable is initialized to true. Then, execute the following operations when shorter is set to true for each node P in the path from the parent node of X to the root node. If shorter is set to false, the algorithm is terminated.

6. Case 1: the balance of the current node P is 0. If its left or right subtree is shortened, its balance is changed to 1 or-1, and shorter is set to false.

7. Case 2: if the balance of node P is not 0 and the height of the subtree is shortened, the balance of node P is changed to 0, and the shorter is set to true.

8. Case 3: if the balance of node P is not 0 and the shorter subtree is shortened, the node P is unbalanced. Balance rotation is required to restore the balance. So that the root of the higher subtree of P is Q (This subtree has not been shortened), according to the Q balance, there are three kinds of balancing operations.

9. Case 3A: if the balance of Q is 0, execute a single rotation to restore the balance of node P and set shorter to false.

10. Case 3B: if the balance of Q is the same as that of P, a single rotation is executed to restore the balance. The balance of node p and q is changed to 0, and the shorter is set to true.

11. Case 3C: if the balance of P is opposite to that of Q, a dual rotation is executed to restore the balance. The Q conversion is performed first and then the P conversion is performed. The balance of the new root node is set to 0, the balance of other nodes is processed accordingly, and the shorter is set to true.

12. In case 3A, 3B, and 3c, the direction of rotation depends on which subtree of node P is shortened.

7.6.4 AVL Tree Height

1. If the AVL tree height is h before the new node is inserted and the number of nodes is N, the time for inserting a new node is O (h ). How big is h for the AVL Tree?

2. Set NH to the number of vertices in the AVL Tree with H. The height of one subtree is h-1, and the height of the other subtree is H-2, which is also highly balanced. So there is a N-1 = 0 (empty tree) N0 = 1 (only the root node) nH = Nh-1 + Nh-2 + 1, h> 0

3. It can be proved that for H? 0, with nH = FH + 3-1.

4. The height of the AVL Tree with N nodes cannot exceed

5. The time required to delete a node in the AVL Tree and perform a balanced rotation is O (log2n ).

6. the binary search tree is suitable for small indexes (or directories) in the memory of the Organization ). For large file systems stored in external storage, it is not appropriate to use a binary search tree to organize indexes.

7. In the file retrieval system, the B _ tree or B + tree is widely used for file indexing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.