轉載請註明出處: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;elsereturn true;}
完整代碼:
/**********************************************題目描述:判斷一棵二叉樹是否平衡,這裡平衡的意思是:該樹種任意兩個葉子節點到根節點的距離之差不大於1Date: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");elseprintf("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;elsereturn true;}
測試結果:
註:代碼開源到Github:https://github.com/mmc-maodun/CareerCup