平衡二叉树的判定

题目 平衡二叉树的判定

在二叉树节点中存放其平衡因子,平衡因子就是左子树和右子树的高度差,只要平衡因子的绝对值全部小于等于1就是平衡树

#include<iostream>
using namespace std;
typedef struct Tree
{
	char data;
	struct Tree *l;
	struct Tree *r;
	int yinzi;
}tree;
int jue(int n)
{
	if(n<0)
	return -n;
}
void creat(tree *&p)
{
	char x;
	cin>>x;
	if(x=='#')return ;
	p=new tree;
	p->data =x;
	p->l =NULL;
	p->r =NULL;
	creat(p->l );
	creat(p->r );
}
int high(tree *p)    //求高度
{
	if(p==NULL)return 0;
	else return high(p->l )>=high(p->r )?high(p->l )+1:high(p->r )+1;
}
void judge(tree *&p,int &flag)
{
	if(p==NULL)return;
	p->yinzi =high(p->l )-high(p->r );    //左右子树高度差
	if(jue(p->yinzi )>1)
		flag=0;
	judge(p->l ,flag);
	judge(p->r ,flag);   //递归处理每一个节点
}
int main()
{
	tree *t;
	creat(t);
	int flag=1;
	judge(t,flag);
	if(flag==1)cout<<"yes!";
	else cout<<"no!";
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/acdalao/article/details/80097711