# 1020 Tree Traversals

（今天很emo，没怎么做事，来灌个水

## 题面

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

### Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

### Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

### Sample Input:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

### Sample Output:

4 1 6 3 5 7 2

## 解

// 中后序建树+层序遍历，一遍过
#include <cstdio>
#include <iostream>
#include <queue>
#define MAXN 100001
using namespace std;
struct node
{
int v;
node *l;
node *r;
};
int in[MAXN];
int mappost[MAXN]; // 节点值对下标的反映射，空间换时间方便找
int post[MAXN];

int n;
void init()
{
for (int i = 1; i <= n; i++)
{
mappost[post[i]] = i;
}
}
node *findroot(int inl, int inr, int postl, int postr) //包含头尾，递归分治
{
if (inl > inr)
{
return NULL;
}
node *c = new node();
c->v = post[postr];
int i, j;
for (i = inl; i <= inr; i++)
{
if (in[i] == post[postr])
{
break;
}
}
int m = -1;
for (j = inl; j <= i - 1; j++)
{
m = max(m, mappost[in[j]]);
}
c->l = findroot(inl, i - 1, postl, m);
c->r = findroot(i + 1, inr, m + 1, postr - 1);
return c;
}
node *root;
void LOT() //层序遍历
{
queue<node *> q;
q.push(root);
while (!q.empty())
{
node *c = q.front();
q.pop();

cout << c->v;
if (c->l != NULL)
{
q.push(c->l);
}
if (c->r != NULL)
{
q.push(c->r);
}
if (!q.empty())
{
cout << " ";
}
}
}

int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> post[i];
}
for (int i = 1; i <= n; i++)
{
cin >> in[i];
}
init();
root = findroot(1, n, 1, n);
LOT();
return 0;
}

Subscribe 1 评论
Inline Feedbacks
View all comments