程序员面试题精选100题(50)-树的子结构.

来源:互联网 发布:淘宝助理初始化40% 编辑:程序博客网 时间:2024/06/09 16:13
// 程序员面试题精选100题(50)-树的子结构.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);}}bool isContain(TNode* rootparent,TNode* rootchild){if (rootparent==NULL&&rootchild!=NULL){return false;}elseif (rootparent!=NULL&&rootchild!=NULL){if (rootparent->chValue==rootchild->chValue){return isContain(rootparent->leftChild,rootchild->leftChild)&isContain(rootparent->rightChild,rootchild->rightChild);}else{if(isContain(rootparent->leftChild,rootchild))return true;elsereturn isContain(rootparent->rightChild,rootchild);}}elsereturn true;// rootparent==NULL&&rootchild==NULL or rootparent!=NULL&&rootchild==NULL}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<<"input m"<<endl;cin>>m;char *preOrder2=new char[m];char *midOrder2=new char[m];cout<<"input preorder2"<<endl;for(int i=0;i<m;i++)cin>>preOrder2[i];cout<<"input midorder2"<<endl;for(int i=0;i<m;i++)cin>>midOrder2[i];rootchild=rebuildTree(preOrder2,0,midOrder2,0,m);//preprint(rootchild);cout<<isContain(rootparent,rootchild)<<endl;system("pause");return 0;}