根据二叉树的前序输出和中序输出重建这颗二叉树
剑指offer上的一道题,
思路:前序遇到的第一个元素肯定是根节点,先建立一个根节点,然后将这个值在中序序列中查找他的位置用leftCount记录,找到后将该值左面和右边分别递归。
#include<cstdlib>
#include<cstdio>
#include<iostream>
#include<string>
using namespace std;
typedef struct node{
int data;
struct node * left;
struct node * right;
}BTNode;
BTNode * preCreateByFrontMid(int front[],int mid[],int low,int high)
{
if(low>=high)
return NULL;
BTNode * root=NULL;
root=(BTNode *)malloc(sizeof(BTNode));
root->data=front[0];
root->left=root->right=NULL;
int leftCount=0;
for(int i=low;i<high&&front[0]!=mid[i];leftCount++,i++);
if(low+leftCount<high)
root->left=preCreateByFrontMid(front+1,mid,low,low+leftCount);
if(low+leftCount+1<high)
root->right=preCreateByFrontMid(front+leftCount+1,mid,low+leftCount+1,high);
return root;
}
void midPrint(BTNode * root)
{
if(root)
{
midPrint(root->left);
printf("%5d",root->data);
midPrint(root->right);
}
}
int main(void)
{
int n;
// freopen("C:\\Users\\mu\\Desktop\\1.txt", "r", stdin); //文件输入到标准输入流
cout<<"输入节点数"<<endl;
cin>>n;
int front[n],mid[n];
cout<<"输入前序"<<endl;
for(int i=0;i<n;i++){
cin>>front[i];
}
cout<<"输入中序"<<endl;
for(int i=0;i<n;i++){
cin>>mid[i];
}
//根据前序中序重建二叉树
BTNode * root=NULL;
root=preCreateByFrontMid(front,mid,0,n);
printf("\n");
cout<<"输出中序:"<<endl;
midPrint(root);
}