标签:
方法一
算法思想:用后序遍历的方式遍历二叉树的每一个结点,在遍历到一个结点之前我们已经遍历了它的左右子树,只要在遍历每个结点的时候记录下它的高度,我们就可以一边遍历一边判断每个结点是不是平衡的。
代码如下:
1 typedef struct BinaryTree 2 { 3 int data; 4 BinaryTree *lc; 5 BinaryTree *rc; 6 }*BinaryTree; 7 8 bool isBalance(BinaryTree *pRoot,int *depth) 9 { 10 if(!pRoot)//最深处初始化 11 { 12 *depth = 0; 13 return true; 14 } 15 int left,right; 16 if(isBalance(pRoot->lc,&left)&&isBalance(pRoot->rc,&right)) 17 { 18 int diff=left - right; //平衡因子 19 if(diff<=1&&diff>=-1) //判断是否平衡 20 { 21 *depth = 1+(left>right)?left:right;//若平衡,返回深度 22 return true; 23 } 24 } 25 return false; 26 }
方法二(推荐)
通过求出根节点的最大深度和最小深度,最大深度和最小深度之差的绝对值小于或等于1,此二叉树即为平衡二叉树
代码如下:
1 typedef struct BinaryTree 2 { 3 int data; 4 BinaryTree *lc; 5 BinaryTree *rc; 6 }*BinaryTree; 7 //求最大值 8 int max(int a,int b) 9 { 10 return (a>b)?a:b; 11 } 12 //求最小值 13 int min(int a,int b) 14 { 15 return (a<b)?a:b; 16 } 17 //求最大深度 18 int maxDepth(BinaryTree T) 19 { 20 if(!T) 21 return 0; 22 return 1+max(maxDepth(T->lc),maxDepth(T->rc)); 23 } 24 //求最小深度 25 int minDepth(BinaryTree T) 26 { 27 if(!T) 28 return 0; 29 return 1+min(minDepth(T->lc),minDepth(T->rc)); 30 } 31 //判断是否平衡二叉树 32 bool isBalance(BinaryTree T) 33 { 34 return (maxDepth(T)-minDepth(T)<=1); 35 }
标签:
原文地址:http://www.cnblogs.com/houjun/p/4862153.html