Introduction to Algorithms 13th Chapter Exercise 13-3--avl Tree (height balance tree) C + + code detailed implementation __web

Source: Internet
Author: User

AVL Tree is a highly balanced tree, for each node, the height of the left subtree and the height of the right subtree is 1.

The AVL tree is a more balanced tree than the red-black tree (the ratio of the height of the left and right subtrees in the red-black tree is less than 2).

The AVL tree is no different from the normal two-fork lookup tree except for its good balance. Therefore, the implementation of the AVL tree code can be based on the previous two-fork tree implementation of the Code algorithm introduction 12th-Two fork lookup Tree of C + + code implementation. The key to implement AVL tree is to maintain the balance of tree. So every insertion of a node or deletion is likely to flip the tree to satisfy the balance. The flip method is the left and right rotation mentioned in the red and black tree. Rotate the tree according to the different conditions that appear.

Although the idea is clear, but to achieve more trouble. The following steps are required:

1. After inserting a node or deleting a node, first locate the maximum height node and the minimum height node in the tree: Lnode,snode

2, then find the most recent common ancestor of Lnode and Snode.

3, according to the recent common ancestor and the location of two nodes we can be divided into four kinds of cases of rotation processing.

Situation one: Lnode on the left side of ANS's right child, the right child (12) is right-handed, ans (6) L.

The condition 2:lnode on the right side of the ANS right child is ans-L.

Situation three: Lnode is left of ans left, ans left child (6) right-handed, ancestor right rotation

Error Correction: Node 4 There should be a right child

Situation four: ans Right rotation

Error Correction: 12 nodes should have a left child.

The specific implementation code is as follows:

BinTreeNode.h

#include <iostream> using namespace std;
Class Bintree;
	Class Bintreenode {private:friend bintree;
	int key;
	Add node height record int height;
	Bintreenode* left;
	bintreenode* right;
bintreenode* parent; Public:bintreenode (): Key ( -1), height (0), left (null), Right (NULL), parent (null) {} bintreenode (bintreenode* node): Key (
	Node->key), height (node->height), left (Node->left), right (Node->right), parent (node->parent) {}
	Bintreenode (int num): Left (null), Right (null), key (num) {} ~bintreenode () {} int getkey () {return key;
	} bintreenode* GetLeft () {return this->left;
	} bintreenode* GetRight () {return this->right;
			} void Inorder () {if (this!=null) {this->left->inorder ();
			cout<<this->key<< "";
		This->right->inorder ();
			} void Preorder () {if (this!=null) {cout<<this->key<< ";
			This->left->preorder ();
		This->right->preorder ();
			} void Postorder () {if (this!=null) {This->left->postorder ();
			This->right->postorder ();
		cout<<this->key<< "";
			} void Makeempty () {if (this!=null) {this->left->makeempty ();
			This->right->makeempty ();
		Delete this;
		an int getheight () {int l,r;
		if (this==null) {return 0;
		} l=this->left->getheight ();
		R=this->right->getheight (); Return 1+ (l>r?)
	L:R); }

};


BinTree.h

#include "BinTreeNode.h" #include <string> #include <bitset> #include <queue> class Bintree {private:
	bintreenode* Root;
	Recording nodes with the maximum height bintreenode* lnode;
Recording nodes with the minimum height bintreenode* snode; Public:bintree (): Root (null), Lnode (null), Snode (null) {}//Bintree (bintreenode* node): root (node) {} ~bintree () {Makeem
		Pty ();
		Lnode=null;
	Snode=null;
		} void Makeempty () {Bintreenode *p=root;
	P->makeempty ();
	int Getkey (bintreenode* node) {return Node->getkey ();
	} bintreenode* Getroot () {return root;
	int GetHeight (bintreenode*node) {return node->height;
	} void Inorder () {return root->inorder ();
	} void Preorder () {return root->preorder ();
	} void Posetorder () {return root->postorder ();
	//Adjust the height of the tree so that the difference in height of each branch of the tree is less than 2.
		void Adjustheight () {//If two node height difference is less than 2, you do not need to adjust if (lnode->height-snode->height<2) {return;
		int num;
		Bintreenode*ans=findnearestanc (Lnode,snode,num); If Lnode and Snode in the recent common ancestor ansThe same side of the num==0 means that the root node is only left child or only right child/if (num==0) {//If only the left child, then the left child for the node right rotation if (ans->left!=null) {Rightrotat
			E (ANS);
			Else leftrotate (ans);
			After the rotation, the height of each node may be disrupted and needs to be adjusted Initnodeheight (root,1);
		Return //lnode on the right of the ancestor else if (num==2) {//If the Lnode is on the left of the ancestor right child if (Searchfromnode (lnode->key,ans->right->left)!=
				NULL) {//Right child right-handed rightrotate (ans->right);
			The ancestors left-leftrotate (ans);
			//If Lnode is on the right side of the ancestor's right else {//ancestor left-leftrotate (ans);
			//After rotation, the height of each node may be disrupted and needs to be adjusted Initnodeheight (root,1);
		Return 
				//lnode on the left of the ancestor else {//if lnode on the Zuo side of the left child of the ancestor if (Searchfromnode (lnode->key,ans->left->left)!=null) {
			The ancestors left-rightrotate (ans);
				//If the Node1 is on the left side of the ancestor of the child else {//left leftrotate (ans->left);
			Ancestor right-rightrotate (ans);
			//After rotation, the height of each node may be disrupted and needs to be adjusted Initnodeheight (root,1);
		Return }//non-recursive version void Insert (int num) {bintreenode* NoDe=new bintreenode (num);
		bintreenode* p=root,*q;
			if (root==null) {root=node;
			root->parent=null;
			root->height=1;
			The maximum height node and the minimum height node are root lnode=snode=root;
		return; while (p) {if (p->key==num) {cout<<num<< "has exist!"
				<<endl;
			return;
				else if (p->key>num) {q=p;
			p=p->left;
				else {q=p;
			p=p->right;
			} if (Q->key>num) {q->left=node;
			node->parent=q;
		node->height=q->height+1;
			else {q->right=node;
			node->parent=q;
		node->height=q->height+1;
		///MAX height node lookup/* if (lnode->height<node->height) {lnode=node;
		}*///min height node lookup/Find maximum height node and min height node findminheightnode (); 
		Findmaxheightnode (root);
	Adjust the height of the Shu adjustheight ();
		//recursive version, the following two functions together constitute the recursive insert function void Reinsert (bintreenode* node,bintreenode* start) {bintreenode* p=start; if (p->key==node->key) {cout<< "the" <<node->key<< "has exist!"
			<<endl;
		return;
				The else if (P->key>node->key) {if (p->left==null) {p->left=node;
				node->parent=p;
			return;
		} reinsert (Node,p->left);
				} else {if (p->right==null) {p->right=node;
				node->parent=p;
			return;
		} reinsert (Node,p->right);
		} void Recinsert (int num) {bintreenode* node=new bintreenode (num);
			if (root==null) {root=node;
			root->parent=null;
		return;
	} reinsert (Node,root);
		///Adjust the height void initnodeheight (bintreenode*node,int num) {Bintreenode*p=node of each node of the tree with node as the root node;
			if (p!=null) {p->height=num;
			Initnodeheight (p->left,num+1);
		Initnodeheight (p->right,num+1); Find the nearest common ancestor, use two queues, place the direct ancestor of Node1 into the QU1, place the direct ancestor of Node2 into the QU2//and then look for the same smallest node from the two team heads, the nearest common ancestor of Node1 and Node2
	Num 0 o'clock represents two nodes not in accordance with the recent common ancestor one left and one right distribution, num to 1 o'clock represents Node1 on the left, Node2 on the right//num for the 2 O'Clock Representative node1 on the right, Node2 on the left, the num in the height of the tree to adjust the time used. Bintreenode*findnearestanc (Bintreenode*node1,bintreenode*node2,int &num) {if (node1==node2) {num=0;
		return node1;
		} queue<bintreenode*>qu1;
		queue<bintreenode*>qu2;
		Bintreenode*p=root,*nod=root;
			The two while loop places the direct ancestors of Node1 and Node2 and their nodes in the QU1 and Qu2 while (p) {Qu1.push);
			if (P->key==node1->key) {break;
			else if (P->key>node1->key) {p=p->left;
			else {p=p->right;
		}} P=root;
			while (p) {Qu2.push (P);
			if (P->key==node2->key) {break;
			else if (P->key>node2->key) {p=p->left;
			else {p=p->right; Find the same smallest node in qu1 and Qu2 while (!qu1.empty () && (!qu2.empty ())) {if (Qu1.front ()->key==qu2.front ()->
				Key) {Nod=qu1.front ();
				Qu1.pop ();
			Qu2.pop ();
			} else {break; } if (nod==node1| |
		Nod==node2) {num=0;
			} else {if (Searchfromnode (node1->key,nod->left) ==null) {num=2; else num=1;
	return nod;
		///Start searching for bintreenode* search (int num) {bintreenode* p=root from the root node of the tree;
			while (p) {if (p->key==num) {return p;
			else if (p->key>num) {p=p->left;
			else {p=p->right; } cout<< ' There is no ' <<num<< ' in this tree! '
		<<endl;
	return NULL;
		///Start searching for bintreenode* searchfromnode (int num,bintreenode*node) {bintreenode* P=node from node nodes of the tree;
			while (p) {if (p->key==num) {return p;
			else if (p->key>num) {p=p->left;
			else {p=p->right;
	} return NULL;
		//Gets the smallest element of the tree with the node node as the root, and returns the minimum int minnum (bintreenode*node) {bintreenode*p=node;
		while (p->left!=null) {p=p->left;
	Return p->key;
		//Gets the most da element of the tree with the node node as the root, and returns the maximum da value int maxnum (bintreenode*node) {bintreenode*p=node;
		while (p->right!=null) {p=p->right;
	Return p->key; //Gets the smallest element of the tree with the node node as the root node, and returns the bintreenode* MinnUm (bintreenode*node) {bintreenode*p=node;
		while (p->left!=null) {p=p->left;
	} return p;
		//Gets the maximum element of the tree with node nodes as the root bintreenode* maxnum (bintreenode*node) {bintreenode*p=node;
		while (p->right!=null) {p=p->right;
	} return p;
		}//Get the parent node of node nodes, if the root node returns null bintreenode* GetParent (bintreenode*node) {return node->parent;
		/* if (node==root) {return NULL;
		} bintreenode*p=root,*q=p;
			while (p) {if (P->key==node->key) {return q;
				else if (P->key>node->key) {q=p;
			p=p->left;
				else {q=p;
			p=p->right; The following bintreenode*inordersuccessor (Bintreenode*node) {if (node->right!=null) {return minnu of the sequence Traversal in}///
		M (node->right);
			else {bintreenode*p=getparent (node);
				while (p&&node==p->right) {node=p;
			P=getparent (node);
		} return p; The Forward-bintreenode*inordepredecessor (Bintreenode*node) {if (NODE-&G) in-sequence traversal in}}//T;left!=null) {return maxnum (node->left);
			else {bintreenode*p=getparent (node);
				while (P&&node==p->left) {node=p;
			P=getparent (node);
		} return p;  
        } bool Delete (int num) {bintreenode*p,*q,*t;  
        Find the node P p=search (num) with a key value of num;  
        if (p==null) {return 0; //If the P node does not have a child node, remove the IF (p->left==null&&p->right==null) {Q=GETP directly 
			Arent (p);  
				if (p==root) {delete p;
			return 1;  
            } if (P==q->left) {q->left=null;  
            else {q->right=null;  
			//Find the maximum height node and the minimum height node delete p;
			Findminheightnode ();
			Findmaxheightnode (root);
           
            Adjust the height of the Shu adjustheight ();  
        return 1;  
  //If only the right node, then the right node as P's parent's child else if (p->left==null)      {q=getparent (P);
				if (p==root) {root=p->right;
				p->right->parent=null;
				Initnodeheight (p->right,1);  
				Delete p;
				Find maximum height node and minimum height node findminheightnode ();
				Findmaxheightnode (root);
				Adjust the height of the Shu adjustheight ();
			return 1;
				} if (P==q->left) {q->left=p->right;
            p->right->parent=q;  
				else {q->right=p->right;
            p->right->parent=q;
			(////////) Adjust the height value of the child node of the node before deleting a node initnodeheight (p->right,q->height+1); 
			Delete p;
			Find maximum height node and minimum height node findminheightnode ();
			Findmaxheightnode (root);
            Adjust the height of the Shu adjustheight ();  
        return 1; 
			///If only the left node, then the left node as P's parent's child else if (p->right==null) {q=getparent (P);
				if (p==root) {root=p->left;
				p->left->parent=null; Initnodeheight (P->left, 1);  
				Delete p;
				Find maximum height node and minimum height node findminheightnode ();
				Findmaxheightnode (root);
				Adjust the height of the Shu adjustheight ();
			return 1;  
				} if (P==q->left) {q->left=p->left;
            p->left->parent=q;  
				else {q->right=p->left;
            p->left->parent=q;
			(////////before deleting a node, make a height adjustment to the child node of the node initnodeheight (p->left,q->height+1); 
			Delete p;
			Find maximum height node and minimum height node findminheightnode ();
			Findmaxheightnode (root);
             
            Adjust the height of the Shu adjustheight ();  
        return 1; //If both the left and right nodes are available, then the successor of P is found, replacing p else {///finding the successor of P, Q=inordersucces  
            SOR (P);  
            Get Q's parents t=getparent (q);  
            Q's parent left child points to Q's right child, so Q is deleted.
			Since Q is the successor of P, so there is at most a right child, and Q certainly for the parents of the left child, if for the parents of the right child//So q can not become the successor of P t->left=q->right; If(q->right!=null) q->right->parent=t; 
		   To get P's parents, so that P's parents point to Q, and Q's left and right children were P's left and right children t=getparent (p);
			   if (p==root) {root=q;
		   q->parent=null;  
					} else {if (t->left==p) {t->left=q;
				q->parent=t;  
					else {t->right=q;
                q->parent=t;  
			}} q->left=p->left;
            p->left->parent=q; 
			q->right=p->right;
			p->right->parent=q;
			Adjust the child nodes of the node to a high level before deleting a node initnodeheight (root,1);
			Delete p;
			Find maximum height node and minimum height node findminheightnode ();
			Findmaxheightnode (root);
            
            Adjust the height of the Shu adjustheight ();  
        return 1;
		}//L node bool Leftrotate (bintreenode* node) {bintreenode*y; if (node->right==null) {cout<< "can ' t left rotate!"
			<<endl;
		return 0;
		} y=node->right;
		node->right=y->left; if (y->left!=null) {y->left->parent=node;
		} y->parent=node->parent;
		if (node->parent==null) {root=y;
		else if (node->parent->left==node) {node->parent->left=y;
		else {node->parent->right=y;
		} y->left=node;
		node->parent=y;
	return 1; }//Right-rotation node bool Rightrotate (bintreenode* node) {if (node->left==null) {cout<< "can ' t rightrotate!"
			<<endl;
		return 0;
		} bintreenode* x;
		x=node->left;
		node->left=x->right;
		if (x->right!=null) {x->right->parent=node;
		} x->parent=node->parent;
		if (node->parent==null) {root=x;
		else if (node->parent->left==node) {node->parent->left=x;
		else {node->parent->right=x;
		} node->parent=x;
		x->right=node;
	return 1; //Looking for a leaf node with a maximum height node and a minimum height node, the maximum height node can be simply completed in the Insert void Findminheightnode () {if root->left==null| |
			Root->right==null) {snode=root;
		return; }
		The middle order traversal lookup findminheightnodeinnonroot (root); } void Findminheightnodeinnonroot (bintreenode* node) {if (node!=null) {findminheightnodeinnonroot (Node->left)
			; if (node->left==null&&node->right==null) {if (snode->left!=null| |
				Snode->right!=null) {Snode=node;
				else if (snode->height>node->height) {snode=node;
		} findminheightnodeinnonroot (Node->right);
			} void Findmaxheightnode (bintreenode* node) {if (node!=null) {findmaxheightnode (node->left);
			if (node->left==null&&node->right==null) {if (lnode->height<node->height) Lnode=node;
		} findmaxheightnode (Node->right); }
	}
};


Test.cpp

#include "BinTree.h" int main () {int a[12]={15,5,3,12,10,13,6,7,16,20,18,23};
	int b[10]={15,14,13,10,9,8,7,6,5,4};
	int i,num;
	Bintree Tree;
	Bintree AVL; for (i=0;i<12;i++) {tree.
	Insert (A[i]);
	}//Avl.inorder (); Tree.
	Inorder ();
	cout<<endl; Tree.
	Delete (16); Tree.
	Inorder ();
	cout<<endl; Tree.
	Delete (15); Tree.
	Inorder ();
	cout<<endl; Tree.
	Preorder ();
	cout<<endl; Tree.
	Posetorder ();
	cout<<endl; cout<< "The heigth of the" is: "<<tree. GetHeight (tree.

	Getroot ()) <<endl; Tree.
	Insert (13); Tree.
	Insert (100); Tree.
	Inorder ();
	cout<<endl; Tree.
	
	Search (45); cout<< "The node" <<3<< "height is:" <<tree. GetHeight (tree.
	Search (3)) <<endl; if (tree. Delete (5)) {cout<< "delete" <<5<< "successful!"
	<<endl; } cout<< "The node" <<3<< "height is:" <<tree. GetHeight (tree.
	Search (3)) <<endl; Tree.
	Inorder ();
	cout<<endl; cout<< "The min Num of the tree is: <<tree. Minnum (tree.
	Getroot ()) <<endl; cout<< "The Max Num is:" <<tree. Maxnum (tree.
	Getroot ()) <<endl; cout<< "The successor of Element 7 is:" <<tree. Inordersuccessor (tree.
	Search (7))->getkey () <<endl; cout<< "The predecessor of Element 7 is:" <<tree. Inordepredecessor (tree.
	Search (7))->getkey () <<endl; cout<< "The successor of element is:" <<tree. Inordersuccessor (tree.
	Search)->getkey () <<endl; cout<< "The commen ans of" <<3<< "and" <<6<< "is:" <<tree. Findnearestanc (tree. Search (3), tree.
	Search (6), num)->getkey () <<endl;
	cout<<num<<endl; cout<< "The commen ans of" <<7<< "and" <<13<< "is:" <<tree. Findnearestanc (tree. Search (7), tree.
	Search (num)->getkey () <<endl;
	
	cout<<num<<endl;
return 0; }


 

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.