如何判断一棵树是平衡二叉树
首先,想一下平衡二叉树的概念。
平衡二叉树(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); } }