PAT1123. Is It a Complete AVL Tree (30)(二叉平衡树模板)

本文介绍了一种自平衡二叉搜索树——AVL树的实现方法,包括节点结构定义、基本操作如插入等,并演示了如何通过层次遍历来判断AVL树是否为完全二叉树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//#include "stdafx.h"
#include<cstdio>
#include<iostream>
#include<string>
#include<algorithm>
#include<set>
#include<queue>
using namespace std;
const int maxn=40;
int n;
struct node{
	int height,data;
	node*l ,*r;

};
node* newnode(int data){
	node* root=new node;
	root->data=data;
	root->height=1;
	root->l=root->r=NULL;
	return root;

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

}

void updateheight(node *&root){
	root->height=max(getheight(root->l),getheight(root->r))+1;

}
int getbalancefactor(node *root){

	return getheight(root->l)-getheight(root->r);

}
void left(node *&root){
	node *temp=root->r;
	root->r=temp->l;
	temp->l=root;
	updateheight(root);
	updateheight(temp);
	root=temp;
}
void right(node *&root){
	node *temp=root->l;
	root->l=temp->r;
	temp->r=root;
	updateheight(root);
	updateheight(temp);
	root=temp;

}
void insert(node *&root,int x){
	if(root==NULL)root=newnode(x);
	else if(root->data>x){
		insert(root->l,x);
		updateheight(root);
		if(getbalancefactor(root)==2){
			if(getbalancefactor(root->l)==1){
				right(root);
			}
			else  if(getbalancefactor(root->l)==-1){
				left(root->l);
				right(root);

			}


		}}

	else{insert(root->r,x);
	updateheight(root);
	if(getbalancefactor(root)==-2){
		if(getbalancefactor(root->r)==-1)
		{ left(root);

		}
		else {
			right(root->r);
			left(root);

		}

	}



	}




}






int main(){

	//  freopen("c://jin.txt","r",stdin);
	int n;
	int a;
	node *root=NULL;
	cin>>n;

	for(int i=0;i<n;i++)
	{cin>>a;
	insert(root,a);
	}
	queue<node*>q;
	q.push(root);
	int num=0;
	int flag=0;
	while(!q.empty()){//判断是不是一棵完全二叉树:层次遍历,遍历到空之后出现不空 就不是
		node* f=q.front();
		q.pop();//pop()一定要紧跟q.front();
		if(f==NULL){
			while(!q.empty()){
				f=q.front();
				q.pop();
				if(f!=NULL){
					flag=1;
					break;}
			}
		}
		if(f==NULL)break;
		cout<<f->data;
		num++;
		if(num!=n)cout<<" ";
		q.push(f->l);
		q.push(f->r);

	}
	cout<<endl;
	if(flag)cout<<"NO"<<endl;
	else cout<<"YES"<<endl;


	//	freopen("CON","r",stdin);
	//	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值