PAT A1123 Is It a Complete AVL Tree(30 分)

//pat A1123 Is It a Complete AVL Tree(30 分)
#include  
#include 
#include 
using namespace std;
const int maxn=30;

int n;

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

node* newNode(int x){
	node* root=new node;
	root->data=x;
	root->height=1;
	root->left=root->right=NULL;
	return root;
}

int getHeight(node* root){
	if(root==NULL){
		return 0;
	}
	else{
		return root->height;
	}
}

int getBalanceFactor(node* root){
	return getHeight(root->left)-getHeight(root->right);
}

void updateHeight(node* root){
	root->height=max(getHeight(root->left),getHeight(root->right))+1;
}

void L(node* &root){
	node* temp=root->right;
	root->right=temp->left;
	temp->left=root;
	updateHeight(root);
	updateHeight(temp);
	root=temp;
}

void R(node* &root){
	node* temp=root->left;
	root->left=temp->right;
	temp->right=root;
	updateHeight(root);
	updateHeight(temp);
	root=temp;
}

void insert(node* &root,int x){
	if(root==NULL){
		root=newNode(x);
		return;
	}
	if(xdata){
		insert(root->left,x);
		updateHeight(root);
		if(getBalanceFactor(root)==2){
			if(getBalanceFactor(root->left)==1){
				R(root);
			}
			else if(getBalanceFactor(root->left)==-1){
				L(root->left);
				R(root);
			}
		}
	}
	else{
		insert(root->right,x);
		updateHeight(root);
		if(getBalanceFactor(root)==-2){
			if(getBalanceFactor(root->right)==-1){
				L(root);
			}
			else if(getBalanceFactor(root->right)==1){
				R(root->right);
				L(root);
			}
		}
	}
}

bool flag=true;
int num=0;
void BFS(node* root){
	queue q;
	q.push(root);
	while(!q.empty()){
		node* now=q.front();
		q.pop();
		if(now!=NULL){
			printf("%d",now->data);
	
			if(num!=n-1){
				printf(" ");	
			}
			else{
				printf("\n");
			}
			num++;
			q.push(now->left);
			q.push(now->right);
		}
		else{
			flag=false;
		}
		if(num>=n){
			break;
		}
	}
}

int main(){
	scanf("%d",&n);
	node* root=NULL;
	int number;
	for(int i=0;i

 

你可能感兴趣的:(PAT A1123 Is It a Complete AVL Tree(30 分))