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

平衡二叉树(AVL树)是满足下面条件的二叉树:

要么是一棵空树,要么左右子树都是AVL树,并且左右子树的深度之差的绝对值不大于1。

由此可知,要判断一棵树是不是AVL树,只要判断它的左右子树的深度之差。问题落到了如何求一棵树的深度上去了。

下面使用递归的方法求一棵树的深度:

[cpp]  view plain copy
  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #include<malloc.h>  
  4. typedef struct BTree  
  5. {  
  6.     int data;  
  7.     struct BTree *lchild,*rchild;  
  8. }BTree,*Root;  
  9. int isAVL(Root root)  
  10. {  
  11.     if(!root)  
  12.                 return TRUE;  
  13.         int ldepth=getDepth(root->lchild);  
  14.         int rdepth=getDepth(root->rchild);  
  15.         int abs_depth=abs(ldepth-rdepth);  
  16.         printf("ldepth=%d,rdepth=%d\n",ldepth,rdepth);  
  17.         return (abs_depth<=1)&&isAVL(root->lchild)&&isAVL(root->rchild);  
  18. }  
  19. int getDepth(Root root)  
  20. {  
  21.     int  ldepth,rdepth;  
  22.     if(!root)  
  23.         return  0;  
  24.     else  
  25.     {  
  26.         rdepth=getDepth(root->rchild);  
  27.         ldepth=getDepth(root->lchild);  
  28.         return (rdepth>ldepth)?(rdepth+1):(ldepth+1);  
  29.     }  
  30. }  
  31. Root createBTree(int arr[],int len,int i)  
  32. {  
  33.     Root root;  
  34.     if(i>=len||(arr[i]==0))  
  35.         return NULL;  
  36. //  printf("i=%d,len=%d,arr[i]=%d\n",i,len,arr[i]);  
  37.     root=(Root)malloc(sizeof(BTree));  
  38.     root->data=arr[i];  
  39.     root->lchild=createBTree(arr,len,2*i);  
  40.     root->rchild=createBTree(arr,len,2*i+1);  
  41.   
  42.     return root;  
  43. }  
  44. void destroyBtree()  
  45. {  
  46.   
  47. }  
  48. int main(void)  
  49. {  
  50.     int arr[]={0,1,2,3,4,0,0,0};  
  51.     //int arr[]={0,1,2,0,4,0,0,0,8};  
  52.     int i,depth;  
  53.     //Root root=createBTree(arr,9,1);  
  54.     Root root=createBTree(arr,8,1);  
  55. //  if(root)        printf("ok\n");  
  56.     printf("depth=%d",getDepth(root));  
  57.     if(isAVL(root))  
  58.         printf("是AVL树\n");  
  59.     else  
  60.         printf("不是AVL树");  
  61. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值