Root of AVL Tree (insertion and rotation of AVL tree)

04-Tree 5 Root of AVL Tree (25 points)

An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.

Now given a sequence of insertions, you are supposed to tell the root of the resulting AVL tree.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (20) which is the total number of keys to be inserted. Then N distinct integer keys are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the root of the resulting AVL tree in one line.

Sample Input 1:

5
88 70 61 96 120

Sample Output 1:

70

Sample Input 2:

7
88 70 61 96 120 90 65

Sample Output 2:

88

Main idea: build a balanced binary tree and return its root node

AC code:

#include <cstdio>   
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <list>
#include <map>
#include <stack>
#include <queue>
using namespace std;
#define ll long long
typedef struct AVLNode
{
	int data;
	int height;
	AVLNode *l,*r;	
}*AVLTree;
int Getheight (AVLTree A)
{
	if(!A)
		return 0;
	else
		return A->height;
}
AVLTree  LeftRotation(AVLTree A)
{
	AVLTree B = A->l;
	A->l = B->r;
	B->r = A;
	A->height = max(Getheight(A->l),Getheight(A->r))+1;
	B->height = max(Getheight(B->l),A->height)+1;
	return B;
}
AVLTree RightRotation(AVLTree A)
{
	AVLTree B = A->r;
	A->r = B->l;
	B->l = A;
	A->height = max(Getheight(A->l),Getheight(A->r))+1;
	B->height = max(A->height,Getheight(B->r))+1;
	return B;
}
AVLTree LeftRightRotation(AVLTree A)
{
	A->l = RightRotation(A->l);
	return LeftRotation(A);
}
AVLTree RightLeftRotation(AVLTree A)
{
	A->r = LeftRotation(A->r);
	return RightRotation(A);
}
AVLTree Insert(AVLTree T,int x)
{
	if(!T)
	{
		T = new AVLNode;
		T->data = x;
		T->height = 1;
		T->l = T->r = NULL;
	}
	else if(x < T->data)
	{
		T->l = Insert(T->l,x);
		if(Getheight(T->l)-Getheight(T->r) == 2)
		{
			if(x < T->l->data)
				T = LeftRotation(T);
			else
				T = LeftRightRotation(T);
		}
	}
	else if(x > T->data)
	{
		T->r = Insert(T->r,x);
		if(Getheight(T->r)-Getheight(T->l) == 2)
		{
			if(x > T->r->data)
				T = RightRotation(T);
			else
				T = RightLeftRotation(T);
		}
	}
	T->height = max(Getheight(T->l),Getheight(T->r))+1;
	return T;
}
intmain()
{
	int n;
	while(cin >> n)
	{
		AVLTree T;
		T = NULL;
		while(n--)
		{
			int x;
			cin >> x;
			T = Insert(T,x);
		}
		cout << T->data <<endl;
	}
    //cout << "AC" <<endl;
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325610772&siteId=291194637