核心算法:
bool isBalanced(pTree pT,int *depth) { if(!pT)//参数判断 { *depth = 0; return true; } //后序遍历 int left,right; if(isBalanced(pT->lChild,&left) && isBalanced(pT->rChild,&right)) { int differ = left-right; if(differ >= -1 && differ <= 1) { //记录深度 *depth = (left > right) ? left+1 : right+1; return true; } } return false; } bool isBalanced(pTree root)//传入二叉树根节点 { int depth = 0; return isBalanced(root,&depth); }
/********************************* 判断二叉树是否是平衡二叉树 by Rowandjj 2014/7/13 *********************************/ #include<iostream> using namespace std; typedef struct _NODE_ { int data; struct _NODE_ *lChild; struct _NODE_ *rChild; }TreeNode,*pTree; void Create(pTree *pT) { int e; cin>>e; if(e != -1) { *pT = (TreeNode*)malloc(sizeof(TreeNode)); if(!pT) { exit(-1); } (*pT)->data = e; (*pT)->lChild = NULL; (*pT)->rChild = NULL; Create(&(*pT)->lChild); Create(&(*pT)->rChild); } } bool isBalanced(pTree pT,int *depth) { if(!pT) { *depth = 0; return true; } int left,right; if(isBalanced(pT->lChild,&left) && isBalanced(pT->rChild,&right)) { int differ = left-right; if(differ >= -1 && differ <= 1) { *depth = (left > right) ? left+1 : right+1; return true; } } return false; } bool isBalanced(pTree root)//传入二叉树根节点 { int depth = 0; return isBalanced(root,&depth); } void travel(pTree pT) { if(pT != NULL) { travel(pT->lChild); travel(pT->rChild); cout<<pT->data<<" "; } } int main() { pTree pT; Create(&pT); travel(pT); cout<<endl; cout<<isBalanced(pT); return 0; }
原文地址:http://blog.csdn.net/chdjj/article/details/37739127