程序员面试题精选100题(60)-判断二叉树是不是平衡

来源:互联网 发布:海量数据存储与管理 编辑:程序博客网 时间:2024/06/10 03:40
// 程序员面试题精选100题(60)-判断二叉树是不是平衡.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>using namespace std;struct TNode{char chValue;TNode *leftChild;TNode *rightChild;};TNode* rebuildTree(char *preOrder,int start1,char *midOrder,int start2,int n)//根据前序和中序建立二叉树 长度为N{TNode *root;if(n==0) return NULL;root = new TNode;int pivet;char chroot;chroot=preOrder[start1];root->chValue = chroot;for(int i=start2;i<start2+n;i++)//include start1 {if(midOrder[i]==chroot) { pivet = i;break;}}if(pivet-start2>0)root->leftChild=rebuildTree(preOrder,start1+1,midOrder,start2,pivet-start2);else root->leftChild = NULL;if(n-pivet+start2-1>0)//pivet-start2 is the half number,root->rightChild=rebuildTree(preOrder,start1+1+pivet-start2,midOrder,pivet+1,n-pivet+start2-1);else root->rightChild = NULL;return root;}void preprint(TNode *root){if(root!=NULL){cout<<root->chValue<<" ";preprint(root->leftChild);preprint(root->rightChild);}}int flag=1;int isbalance(TNode *root){if (flag==0){return -1;}if (root==NULL){return 0;}int h1=isbalance(root->leftChild)+1;int h2=isbalance(root->rightChild)+1;if (abs(h1-h2)>1){flag=0;}return h1>h2?h1:h2;}//////////////////////////////////////////////////////////////////////////bool IsBalanced(TNode* pRoot, int* pDepth){if(pRoot == NULL){*pDepth = 0;return true;}int left, right;if(IsBalanced(pRoot->leftChild, &left)&& IsBalanced(pRoot->rightChild, &right)){int diff = left - right;if(diff <= 1 && diff >= -1){*pDepth = 1 + (left > right ? left : right);return true;}}return false;}bool IsBalanced(TNode* pRoot){int depth = 0;return IsBalanced(pRoot, &depth);}int _tmain(int argc, _TCHAR* argv[]){TNode* rootparent,*rootchild;int n,m;cout<<"input n"<<endl;cin>>n;char *preOrder=new char[n];char *midOrder=new char[n];cout<<"input preorder1"<<endl;for(int i=0;i<n;i++)cin>>preOrder[i];cout<<"input midorder1"<<endl;for(int i=0;i<n;i++)cin>>midOrder[i];rootparent=rebuildTree(preOrder,0,midOrder,0,n);preprint(rootparent);cout<<endl;isbalance(rootparent);if (flag==1){cout<<"is balance "<<endl;}else{cout<<"is not balance "<<endl;}cout<<IsBalanced(rootparent);system("pause");return 0;}
自己的程序好像不是很规范,或说不专业
原创粉丝点击