码迷,mamicode.com
首页 > 其他好文 > 详细

A11231123 Is It a Complete AVL Tree (30分)

时间:2020-06-05 22:37:58      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:void   pop   com   ret   tree   ios   amp   empty   new   

一、技术总结

二、参考代码

#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("\n%s", isComplete ? "YES" : "NO");
	return 0;
}

A11231123 Is It a Complete AVL Tree (30分)

标签:void   pop   com   ret   tree   ios   amp   empty   new   

原文地址:https://www.cnblogs.com/tsruixi/p/13052439.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!