平衡二叉树:
每个节点的左右子树高度差不大于1的二叉树。
方法:
递归探索每个节点的左右子树,并判断高度差是否大于一。
代码:
#include <iostream>
#include <algorithm>
using namespace std;
#define int long long
struct node{
char val;
node *l,*r;
};
int flag;
node* build(){
node *T;
char ch; cin>>ch;
if(ch=='#'){
T=NULL;
}
else {
T=new node;
T->val=ch;
T->l=build();
T->r=build();
}
return T;
}
int pand(node* T){
if(T==NULL) return 0;
else {
int t=pand(T->l);
int s=pand(T->r);
if(abs(t-s)>1) flag=1;
return max(t,s)+1;
}
}
signed main(){
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
node *root=new node;
root=build();
int t=pand(root);
if(flag==0) cout<<"yes!";
if(flag==1) cout<<"no!";
return 0;
}