1066 Root of AVL Tree(25 分)

1066 Root of AVL Tree(25 分)

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

经过俩个小时的努力终于把AVL最基本的用法整出来了。 

code

#pragma warning(disable:4996)
#include <iostream>
#include <algorithm>
using namespace std;
class AVLtree {
public:
	int value=0, bf=0, height = 0;
	AVLtree *left = NULL, *right = NULL;
	AVLtree* opLL() {
		AVLtree* pa = this, *pb = left, *pc = ((left)->left);
		pa->left = pb->right;
		pb->right = pa;
		return pb;
	}
	AVLtree* opRR() {
		AVLtree* pa = this, *pb = right, *pc = (right->right);
		pa->right = pb->left;
		pb->left = pa;
		return pb;
	}
	AVLtree* opRL() {
		AVLtree* pa = this, *pb = right, *pc = (right->left);
		pb->left = pc->right;
		pc->right = pb;
		pa->right = pc->left;
		pc->left = pa;
		return pc;
	}
	AVLtree* opLR() {
		AVLtree* pa = this, *pb = left, *pc = (left->right);
		pb->right = pc->left;
		pc->left = pb;
		pa->left = pc->right;
		pc->right = pa;
		return pc;
	}
};
int getheight(AVLtree* p);
int getbf(AVLtree* p);
AVLtree* insert(AVLtree* p, int x) {
	if (p == NULL) {
		p = new AVLtree;
		p->value = x;
		return p;
	}
	if (x >= p->value) p->right = insert(p->right, x);
	else  p->left = insert(p->left, x);
	return p;
}
AVLtree* blance(AVLtree* p) {
	if (p == NULL)	 return NULL;
	p->left = blance(p->left);
	p->right = blance(p->right);
	if (getbf(p) > 1) {
		if (getbf(p->left) > 0) p = p->opLL();
		else p = p->opLR();
	}
	else if (getbf(p) < -1) {
		if (getbf(p->right) > 0) p = p->opRL();
		else p = p->opRR();
	}
	return p;
}
int getheight(AVLtree* p) {
	if (p == NULL) return 0;
	return max(getheight(p->left), getheight(p->right)) + 1;
}
int getbf(AVLtree* p) {
	return p->bf = (p->left == NULL ? 0 : getheight(p->left)) - (p->right == NULL ? 0 : getheight(p->right));
}
void print(AVLtree* p) {
	if (p == NULL) return;
	cout << p->value << '-' <<getbf(p)<< ' ';
	print(p->left);
	print(p->right);
}
int main() {
	int n, x;
	cin >> n;
	AVLtree *p=NULL;
	while (n--) {
		cin >> x;
		p = insert(p, x);
		//print(p);
		p = blance(p);
		//print(p);
	}
	cout << p->value << endl;
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Cute_jinx/article/details/82313637