转载请注明出处:http://blog.csdn.net/ns_code/article/details/22756167
题目:
Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.
翻译:
实现一个函数检查一棵树是否平衡。在该问题中,平衡指的是这棵树任意两个叶子结点到根结点的距离之差不大于1。
补充:这里的平衡只要求了任意两个叶子节点的深度之差不大于1,明显跟我们所了解的平衡二叉树不同,所以不要混淆。
思路:
这里需要求每个叶子节点的深度,我们可以选择前、中、后序遍历的任意一种(思路相同,只要移动下代码具体的位置即可)来在遍历的过程中记录叶子节点的深度(当然也可以记录下每个节点的深度,但我们只需要记录下叶子节点的深度即可),我们这里采用中序递归遍历的方法来求解,而且假定该树是二叉树,否则真没法求了。
实现代码:
#define MAX 20 //保存叶子节点深度的数组的最大值 int count = 0; //全局变量,保存叶子节点的个数 int Dep[MAX]; //保存叶子节点深度的数组 /* 中序递归遍历求叶子节点的深度 */ void getDepth(BTree pTree,int depth) { if(pTree) { if(pTree->pLchild) getDepth(pTree->pLchild,depth+1); if(!pTree->pLchild && !pTree->pRchild) Dep[count++] = depth; if(pTree->pRchild) getDepth(pTree->pRchild,depth+1); } } /* 根据数组保存的各叶子节点的深度值,判断该树是否平衡 */ bool weatherBalance(BTree pTree) { if(!pTree) return true; int max = Dep[0]; int min = Dep[0]; int i; for(i=0;i<count;i++) { if(max<Dep[i]) max = Dep[i]; if(min>Dep[i]) min = Dep[i]; } if(max-min>1) return false; else return true; }
完整代码:
/********************************************** 题目描述: 判断一棵二叉树是否平衡,这里平衡的意思是: 该树种任意两个叶子节点到根节点的距离之差不大于1 Date:2014-04-01 ***********************************************/ #include<stdio.h> #include<stdlib.h> #define MAX 20 //保存叶子节点深度的数组的最大值 int count = 0; //全局变量,保存叶子节点的个数 int Dep[MAX]; //保存叶子节点深度的数组 typedef struct BTNode { char data; struct BTNode *pLchild; struct BTNode *pRchild; }BTNode, *BTree; BTree create_tree(); void getDepth(BTree,int); bool weatherBalance(BTree); int main() { BTree pTree = create_tree(); getDepth(pTree,0); if(weatherBalance(pTree)) printf("Balanced\n"); else printf("Not Balanced\n"); return 0; } BTree create_tree() { BTree pA = (BTree)malloc(sizeof(BTNode)); BTree pB = (BTree)malloc(sizeof(BTNode)); BTree pD = (BTree)malloc(sizeof(BTNode)); BTree pE = (BTree)malloc(sizeof(BTNode)); BTree pC = (BTree)malloc(sizeof(BTNode)); BTree pF = (BTree)malloc(sizeof(BTNode)); pA->data = 'A'; pB->data = 'B'; pD->data = 'D'; pE->data = 'E'; pC->data = 'C'; pF->data = 'F'; pA->pLchild = pB; pA->pRchild = pC; pB->pLchild = pD; pB->pRchild = pE; pD->pLchild = pF; pD->pRchild = NULL; pE->pLchild = pE->pRchild = NULL; pC->pLchild = pC->pRchild = NULL; pF->pLchild = pF->pRchild = NULL; return pA; } /* 中序递归遍历求叶子节点的深度 */ void getDepth(BTree pTree,int depth) { if(pTree) { if(pTree->pLchild) getDepth(pTree->pLchild,depth+1); if(!pTree->pLchild && !pTree->pRchild) Dep[count++] = depth; if(pTree->pRchild) getDepth(pTree->pRchild,depth+1); } } /* 根据数组保存的各叶子节点的深度值,判断该 */ bool weatherBalance(BTree pTree) { if(!pTree) return true; int max = Dep[0]; int min = Dep[0]; int i; for(i=0;i<count;i++) { if(max<Dep[i]) max = Dep[i]; if(min>Dep[i]) min = Dep[i]; } if(max-min>1) return false; else return true; }测试结果:
注:代码开源到Github:https://github.com/mmc-maodun/CareerCup