# L2-006 树的遍历 (25分)团体设计天梯赛

#include <bits/stdc++.h>
using namespace std;
const int N = 35;
int postArr[N], inArr[N];
typedef struct Node
{
int v;
Node *lchild;
Node *rchild;
} Node, *Tree;

Tree create(int postL, int postR, int inL, int inR)
{
if (postL > postR)
return NULL;
Tree root = (Tree)malloc(sizeof(Node));
int x = postArr[postR];
root->v = x;
int idx = -1;
for (int i = inL; i <= inR; i++)
{
if (inArr[i] == x)
{
idx = i;
}
}
int cnt = idx - inL;
root->lchild = create(postL, postL + cnt - 1, inL, idx - 1);
root->rchild = create(postL + cnt, postR - 1, idx + 1, inR);
return root;
}
void layerOrder(Tree tree)
{
queue<Tree> Q;
Q.push(tree);
bool flag = false;
while (!Q.empty())
{
Tree T = Q.front();
Q.pop();
if (flag)
{
printf(" ");
}
printf("%d", T->v);
if (T->lchild != NULL)
Q.push(T->lchild);
if (T->rchild != NULL)
Q.push(T->rchild);
flag = true;
}
}
int main(void)
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
scanf("%d", &postArr[i]);
}
for (int i = 0; i < n; i++)
{
scanf("%d", &inArr[i]);
}
Tree tree = create(0, n - 1, 0, n - 1);
layerOrder(tree);
printf("\n");
return 0;
}

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

跑的真快的并快乐的疾风索

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

02-24 1万+
05-17 1971
02-24 2万+
03-18 2445
02-17 1万+
06-16 2046
03-29 2159
09-26 1591
02-23 1万+
11-29 1341
08-06 1310
07-17 2260
05-13 1145
05-15 6756