二叉树构造
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<algorithm>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<string>
using namespace std;
typedef long long ll;
int fro[1010],mid[1010],sum[1010];
struct node
{
int ltree,rtree;
}tree[1010];
int build(int l1,int r1,int l2,int r2)//1中,2前
{
if(l1>r1||l2>r2)
return 0;
int root=fro[l2];
int p=l1;
while(mid[p]!=root)
p++;
int keep=p-l1;
tree[root].ltree=build(l1,p-1,l2+1,l2+keep);
tree[root].rtree=build(p+1,r1,r2-r1+p+1,r2);
return root;
}
int v;
void print(int root)
{
if(tree[root].ltree!=0)
print(tree[root].ltree);
if(tree[root].rtree!=0)
print(tree[root].rtree);
sum[v++]=root;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
v=0;
for(int i=1;i<=n;i++)
scanf("%d",&fro[i]);
for(int j=1;j<=n;j++)
scanf("%d",&mid[j]);
build(1,n,1,n);
print(fro[1]);
for(int i=0;i<n;i++)
{
printf("%d%c",sum[i],i==(n-1)?'\n':' ');
}
}
return 0;
}
311

被折叠的 条评论
为什么被折叠?



