#include <cstdio>
const int SZ = 1 << 20; //提升IO buff
struct fastio{
char inbuf[SZ];
char outbuf[SZ];
fastio(){
setvbuf(stdin, inbuf, _IOFBF, SZ);
setvbuf(stdout, outbuf, _IOFBF, SZ);
}
}io;
const int maxn = 4000010;
int pre[maxn], post[maxn], in[maxn];
int n;
struct node
{
node *lchild, *rchild;
int num;
};
node* createtree (int pre_lo, int pre_hi, int post_lo, int post_hi)
{
node* root = new node;
root->num = pre[pre_lo];
root->rchild = NULL;
root->lchild = NULL;
if(post_lo == post_hi)
return root;
int pos;
for(int i = post_lo; i <= post_hi; i++)
{
if(post[i] == pre[pre_lo + 1])
{
pos = i;
break;
}
}
int numleft = pos - post_lo + 1;
root->lchild = createtree(pre_lo + 1, pre_lo + numleft, post_lo, pos);
root->rchild = createtree(pre_lo + numleft + 1, pre_hi, pos + 1, post_hi - 1);
return root;
}
void inOrder(node *root)
{
if(root->lchild != NULL)
inOrder(root->lchild);
printf("%d ", root->num);
if(root->rchild != NULL)
inOrder(root->rchild);
}
int main()
{
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
scanf("%d", &pre[i]);
}
for(int i = 0; i < n; i++)
{
scanf("%d", &post[i]);
}
node* root = createtree(0, n-1, 0, n-1);
inOrder(root);
return 0;
}
真二叉树重构(Proper Rebuild)
最新推荐文章于 2023-09-21 09:53:26 发布