例如
输入:
124859367
482591637
输出:
123456789
S1:先序遍历的第一个一定是根结点,在中续遍历序列中找到根结点位置
S2:先序遍历的[pre+1,pre+gen]的位置一定是左子树,中序遍历的[mid,mid+gen]一定是左子树,因此递归寻找左子树,build(pre+1,mid,gen)
先序遍历的[pre+gen+1,n]的位置一定是右子树,中序遍历的[mid+gen+1,n]一定是右子树,因此递归寻找右子树,build(pre+1,mid,gen)
S3:由于是递归的,因此最后返回的是根结点
——————————————————————
建树完成,开始层次遍历
——————————————————————
S4:将根结点push入队列
S5:如果队列非空,取队首元素,遍历结点的左右子树,push进队列
S6:输出队首元素的值,弹出队首元素,返回S5
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
#include<queue>
using namespace std;
int n;
int len;
char x[105];//先序遍历
char h[105];//中序遍历
struct tree{
char num;
struct tree *l;
struct tree *r;
};
queue<tree*> s;
int findroot(char *x,char *h,int n)
{
char c = x[0];
for(int i =0;i < n;i++)
{
if(h[i]==c)
return i;
}
return -1;
}
tree* build(char *x,char *h,int n)
{
if(n == 0)
{
return NULL;
}
int gen = findroot(x,h,n);
tree *ro = (tree*)malloc(sizeof(tree));
ro->num = x[0];
//cout<<x[0];
ro->l = build(x+1,h,gen);
ro->r = build(x+gen+1,h+gen+1,n-gen-1);
return ro;
}
void print(tree *root)
{
tree*st;
s.push(root);
while(!s.empty())
{
st = s.front();
printf("%c",st->num);
s.pop();
if(st->l!=NULL)
s.push(st->l);
if(st->r!=NULL)
s.push(st->r);
}
}
int main()
{
scanf("%s",x);
scanf("%s",h);
//printf("%s%s",x,h);
tree *rot = build(x,h,strlen(x));
print(rot);
}