A11231123 Is It a Complete AVL Tree (30分)

Posted tsruixi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了A11231123 Is It a Complete AVL Tree (30分)相关的知识,希望对你有一定的参考价值。

一、技术总结

二、参考代码

#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct node{
	int h, v;
	node* L;
	node* R;
};
node* newNode(int v){
	node* Node = new node;
	Node->v = v;
	Node->h = 1;
	Node->L = Node->R = NULL;
	return Node;
}
int getH(node* root){
	if(root == NULL) return 0;
	return root->h;
}
int getBF(node* root){
	return getH(root->L) - getH(root->R);
}
void UpdateH(node* root){
	root->h = max(getH(root->R), getH(root->L)) + 1;
}
void L(node* &root){
	node* temp = root->R;
	root->R = temp->L;
	temp->L = root;
	UpdateH(root);
	UpdateH(temp);
	root = temp;
}
void R(node* &root){
	node* temp = root->L;
	root->L = temp->R;
	temp->R = root;
	UpdateH(root);
	UpdateH(temp);
	root = temp;
}
void insert(node* &root, int v){
	if(root == NULL){
		root = newNode(v);
		return;
	}
	if(v < root->v){
		insert(root->L, v);
		UpdateH(root);
		if(getBF(root) == 2){
			if(getBF(root->L) == 1){
				R(root);
			}else if(getBF(root->L) == -1){
				L(root->L);
				R(root);
			}
		}
	}else{
		insert(root->R, v);
		UpdateH(root);
		if(getBF(root) == -2){
			if(getBF(root->R) == -1){
				L(root);
			}else if(getBF(root->R) == 1){
				R(root->R);
				L(root);
			}
		}
	}
}
node* Create(int data[], int n){
	node* root = NULL;
	for(int i = 0; i < n; i++){
		insert(root, data[i]);
	}
	return root;
}
int isComplete = 1, after = 0;
vector<int> levelOrder(node* root){
	vector<int> v;
	queue<node*> q;
	q.push(root);
	while(!q.empty()){
		node* temp = q.front();
		q.pop();
		v.push_back(temp->v);
		if(temp->L != NULL){
			if(after) isComplete = 0;
			q.push(temp->L);
		}else{
			after = 1;
		}
		if(temp->R != NULL){
			if(after) isComplete = 0;
			q.push(temp->R);
		}else{
			after = 1;
		}
	} 
	return v;
}
int main(){
	int n, data[25];
	scanf("%d", &n);
	node* root = NULL;
	for(int i = 0; i < n; i++){
		scanf("%d", &data[i]);
	} 
	root = Create(data, n);
	vector<int> v = levelOrder(root);
	for(int i = 0; i < n; i++){
		if(i != 0) printf(" ");
		printf("%d", v[i]);
	} 
	printf("
%s", isComplete ? "YES" : "NO");
	return 0;
}

以上是关于A11231123 Is It a Complete AVL Tree (30分)的主要内容,如果未能解决你的问题,请参考以下文章

poj 1308 Is It A Tree?

Is It A Tree?

Is It A Tree?(并查集)

B - Is It A Tree?

If a thing is worth doing it is worth doing well

Is It A Tree? (并查集)