PAT甲级 1066 Root of AVL Tree (25 分)AVL树

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,也不是很难,关键在于几个关键位置操作熟悉。如果构造AVL的详细解说可以参考我的另一篇博客https://blog.csdn.net/qq_29762941/article/details/81022367 

#include<iostream>
#include<vector>
using namespace std;

struct node{
	int data;
	node *left;
	node *right;
};

void create(node *&bt,vector<int> &arr,int n);
void insert(node *&bt,int data);
int height(node *bt);
int diff(node *bt);
node *balance(node *bt);
node *ll_roate(node *bt);
node *rr_roate(node *bt);
node *lr_roate(node *bt);
node *rl_roate(node *bt);

int main(){
	int n;
	cin>>n;
	vector<int> arr(n);
	for(int i=0;i<n;i++)
		cin>>arr[i];
	node *root = nullptr;
	create(root,arr,n);
	cout<<root->data;
	return 0;
}

void create(node *&bt,vector<int> &arr,int n){
	for(int i=0;i<n;i++)
		insert(bt,arr[i]);
}

void insert(node *&bt,int data){
	if(bt == nullptr)
	{
		bt = new node();
		bt->data = data;
		bt->left = bt->right = nullptr;
		return ;
	}
	if(bt->data == data)
		return ;
	else if(bt->data < data){
		insert(bt->left,data);
		bt = balance(bt);
	}
	else{
		insert(bt->right,data);
		bt = balance(bt);
	}
}

node *balance(node *bt){
	if(diff(bt) > 1){
		if(diff(bt->left) > 0)
			return ll_roate(bt);
		else
			return lr_roate(bt);
	}
	else if(diff(bt) < -1){
		if(diff(bt->right) < 0)
			return rr_roate(bt);
		else
			return rl_roate(bt);
	}
	
	return bt;
}

node *ll_roate(node *bt){
	node *temp = bt->left;
	bt->left = temp->right;
	temp->right = bt;
	return temp;
}

node *rr_roate(node *bt){
	node *temp = bt->right;
	bt->right = temp->left;
	temp->left = bt;
	return temp;
}

node *lr_roate(node *bt){
	node *temp = bt->left;
	bt->left = rr_roate(temp);
	return ll_roate(bt);
}

node *rl_roate(node *bt){
	node *temp = bt->right;
	bt->right = ll_roate(temp);
	return rr_roate(bt);
}

int height(node *bt){
	if(bt == nullptr)
		return 0;
	return max(height(bt->left),height(bt->right)) + 1;
}

int diff(node *bt){
	return height(bt->left) - height(bt->right);
}

猜你喜欢

转载自blog.csdn.net/qq_29762941/article/details/82874488