PAT A1123

这是一个使用C++实现的平衡二叉树算法,包括节点结构定义、高度计算、左右旋操作、平衡因子计算、创建平衡树、层次遍历等方法。程序读取输入的整数N和N个节点值,构造一棵平衡二叉树,并按层次顺序打印节点,最后判断树是否平衡并输出结果。

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

#include <iostream>
#include <queue>
using namespace std;
struct node{
	int data;
	node *lchild,*rchild;
};
int N;
int geth(node *root){
	if(root==NULL) return 0;
	return 1+max(geth(root->lchild),geth(root->rchild));
}
int bfac(node *root){
	return geth(root->lchild)-geth(root->rchild);
}
void R(node* &root){
	node* temp=root->lchild;
	root->lchild=temp->rchild;
	temp->rchild=root;
	root=temp;
}
void L(node* &root){
	node *temp=root->rchild;
	root->rchild=temp->lchild;
	temp->lchild=root;
	root=temp;
}
void createtree(node* &root,int x){
	if(root==NULL){
		root=new node;
		root->data=x;
		root->lchild=root->rchild=NULL;
		return;
	}
	if(x<root->data){
		createtree(root->lchild,x);
		if(bfac(root)==2){
			if(bfac(root->lchild)==1){
				R(root);
			}else if(bfac(root->lchild)==-1){
				L(root->lchild);
				R(root);
			}
		}
	}else{
		createtree(root->rchild,x);
		if(bfac(root)==-2){
			if(bfac(root->rchild)==-1){
				L(root);
			}else if(bfac(root->rchild)==1){
				R(root->rchild);
				L(root);
			}
		}
	}
}
void BFS(node *root){
	queue<node*> q;
	q.push(root);
	int countprint=0;
	bool ans=true;
	while(!q.empty()){
		node* t=q.front();
		q.pop();
		if(t!=NULL){
			printf("%d",t->data);
			if(++countprint<N) printf(" ");
		}else{
			while(!q.empty()&&q.front()==NULL)
				q.pop();
			if(!q.empty()){
				ans=false;
				continue;
			}else break;
		}
		q.push(t->lchild);
		q.push(t->rchild);
	}
	if(ans) printf("\nYES");
	else printf("\nNO");
}
int main(){
	scanf("%d",&N);
	node *root=NULL;
	for(int i=0;i<N;i++){
		int temp;
		scanf("%d",&temp);
		createtree(root,temp);
	}
	BFS(root);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值