SWUST OJ 1077: 平衡二叉树的判定

1077: 平衡二叉树的判定

题目链接-1077: 平衡二叉树的判定
在这里插入图片描述
解题思路
平衡二叉树:是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树

  • 我们先根据先序序列建树,然后判断任意一个节点的左右子树高度差的绝对值是否不超过1
  • 左右子树的最大高度再加1便是父节点的高度,我们可以递归求解树的高度
  • 具体操作见代码

附上代码

#pragma GCC optimize("-Ofast","-funroll-all-loops")
#include<bits/stdc++.h>
#define int long long
#define lowbit(x) (x &(-x))
#define endl '\n'
using namespace std;
const int INF=0x3f3f3f3f;
const int dir[4][2]={-1,0,1,0,0,-1,0,1};
const double PI=acos(-1.0);
const double e=exp(1.0);
const double eps=1e-10;
const int M=1e9+7;
const int N=2e5+10;
typedef long long ll;
typedef pair<int,int> PII;
typedef unsigned long long ull;
struct node{
	char data;
	node *left,*right;
}*p;
void Build(node *&p){//建树
	char c;
	cin>>c;
	if(c=='#')
		p=NULL;
	else{
		p=new node;
		p->data=c;
		Build(p->left);
		Build(p->right);
	}
}
int Depth(node *t){//计算树的高度
	if(t==NULL)
		return 0;
	return Depth(t->left)>Depth(t->right)? Depth(t->left)+1:Depth(t->right)+1;
}
bool Balance(node *&p){//判断该树是否平衡
	if(p==NULL)
		return 1;
	int lh=Depth(p->left);
	int rh=Depth(p->right);
	if(abs(lh-rh)>1)
		return 0;
	return Balance(p->left)&&Balance(p->right);
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	
	Build(p);
	if(Balance(p))
		cout<<"yes!";
	else
		cout<<"no!";
	return 0;
}	
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值