标签:
#include <iostream> using namespace std; struct BinaryTree { int data; BinaryTree *pLeft; BinaryTree *pRight; }; BinaryTree *pRoot1=NULL; int arr[7]={8,5,15,3,7,16,6}; void InserTree(BinaryTree **root,int data) { BinaryTree *temp=new BinaryTree; temp->data=data; temp->pLeft=temp->pRight=NULL; if(NULL==*root) { *root=temp; } else { BinaryTree *current=*root; BinaryTree *back=NULL; while(current) { back=current; if(data > current->data) current=current->pRight; else current=current->pLeft; } if(NULL==back->pLeft) back->pLeft=temp; else back->pRight=temp; } } void CreateTreeLoop(BinaryTree **root,int *array,int length) { for(int i=0;i<length;i++) InserTree(root,array[i]); } void Inorder(BinaryTree *root) { if(NULL!=root) { Inorder(root->pLeft); cout<<root->data<<" "; Inorder(root->pRight); } } int TreeDepth(BinaryTree*root) { if(NULL==root) return 0; int left=TreeDepth(root->pLeft); int right=TreeDepth(root->pRight); return left>right?(left+1):(right+1); } bool IsBalance(BinaryTree *root) { if(NULL==root) return true; int leftIsBla=TreeDepth(root->pLeft); int rightIsBla=TreeDepth(root->pRight); int diff=leftIsBla-rightIsBla; if(diff>1 || diff<-1 ) return false; return IsBalance(root->pLeft) && IsBalance(root->pRight); } int main() { CreateTreeLoop(&pRoot1,arr,7); cout<<"中序遍历:"; Inorder(pRoot1); cout<<endl; bool result=IsBalanced(pRoot1); if(result) cout<<"The tree is balance!"<<endl; else cout<<"The tree is not a balance tree!"<<endl; system("pause"); return 0; }
运行结果:
bool IsBalanceHelp(BinaryTree *root,int *depth) { if(root==NULL) { *depth=0; return true; } int left,right; if(IsBalanceHelp(root->pLeft,&left)&& IsBalanceHelp(root->pRight,&right)) { int diff=left-right; if(diff<=1 && diff>=-1) { *depth=1+(left>right?left:right); //当遍历每个结点时,记录下该结点的深度,下次就不用再遍历已经遍历过的结点; return true; } } return false; } bool IsBalanced(BinaryTree *root) { int depth=0; return IsBalanceHelp(root,&depth); }次种算法避免了不必要的重复计算,对于数据量大的二叉树效率明显提高。
标签:
原文地址:http://blog.csdn.net/gogokongyin/article/details/51712659