如何判断一棵树是平衡二叉树

首先,想一下平衡二叉树的概念。

平衡二叉树(AVL树)是满足下面条件的二叉树:要么是一棵空树,要么左右子树都是AVL树,并且左右子树的深度之差的绝对值不大于1。由此可知,要判断一棵树是不是AVL树,只要判断它的左右子树的深度之差。问题落到了如何求一棵树的深度上去了。下面使用递归的方法求一棵树的深度:

 

#include<stdio.h>
#include<math.h>
#include<malloc.h>
typedef struct BTree
{
	int data;
	struct BTree *lchild,*rchild;
}BTree,*Root;
int isAVL(Root root)
{
	if(!root)
                return TRUE;
        int ldepth=getDepth(root->lchild);
        int rdepth=getDepth(root->rchild);
        int abs_depth=abs(ldepth-rdepth);
        printf("ldepth=%d,rdepth=%d\n",ldepth,rdepth);
        return (abs_depth<=1)&&isAVL(root->lchild)&&isAVL(root->rchild);
}
int getDepth(Root root)
{
	int  ldepth,rdepth;
	if(!root)
		return	0;
	else
	{
		rdepth=getDepth(root->rchild);
		ldepth=getDepth(root->lchild);
		return (rdepth>ldepth)?(rdepth+1):(ldepth+1);
	}
}
Root createBTree(int arr[],int len,int i)
{
	Root root;
	if(i>=len||(arr[i]==0))
		return NULL;
//	printf("i=%d,len=%d,arr[i]=%d\n",i,len,arr[i]);
	root=(Root)malloc(sizeof(BTree));
	root->data=arr[i];
	root->lchild=createBTree(arr,len,2*i);
	root->rchild=createBTree(arr,len,2*i+1);

	return root;
}
void destroyBtree()
{

}
int main(void)
{
	int arr[]={0,1,2,3,4,0,0,0};
	//int arr[]={0,1,2,0,4,0,0,0,8};
	int i,depth;
	//Root root=createBTree(arr,9,1);
	Root root=createBTree(arr,8,1);
//	if(root)		printf("ok\n");
	printf("depth=%d",getDepth(root));
	if(isAVL(root))
		printf("是AVL树\n");
	else
		printf("不是AVL树");
}


在求深度的代码上浪费了很多时间,将我的错误贴出来,希望大家不要再犯。

 

 

int getDepth(Root root)
{
	int  ldepth,rdepth;
	if(!root)
		return	0;
	else if(!root->lchild&&!root->rchild)
		return 1;
	else
	{
		rdepth=getDepth(root->rchild);
		ldepth=getDepth(root->lchild);
		return (rdepth>ldepth)?(rdepth):(ldepth);
	}
}


 





 

转载于:https://www.cnblogs.com/woshizyl/archive/2012/09/04/2800346.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值