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;
}