还原二叉树
Case Time Limit: 100 MS (Others) / 200 MS (Java) Case Memory Limit: 256 MB (Others) / 512 MB (Java)
Accepted: 186 Total Submission: 262
Problem Description
给一棵二叉树的层序遍历序列和中序遍历序列,求这棵二叉树的先序遍历序列和后序遍历序列。
Input
每个输入文件中一组数据。
第一行一个正整数N(1<=N<=30),代表二叉树的结点个数(结点编号为1~N)。接下来两行,每行N个正整数,分别代表二叉树的层序遍历序列和中序遍历序列。数据保证序列中1~N的每个数出现且只出现一次。
Output
输出两行,每行N个正整数,分别代表二叉树的先序遍历序列和后序遍历序列。每行末尾不输出额外的空格。
Sample Input
7
3 5 4 2 6 7 1
2 5 3 6 4 7 1
Sample Output
3 5 2 4 6 7 1
2 5 6 1 7 4 3
Author
Shoutmon
Source
15浙大考研机试模拟赛
主要在于用中序和层序建树,首先来说,第一个层序的节点,一定是根节点,而中序可以把序列分开为根的左右分支,假设中序的序列的下标为InL, InR, 则从左往右遍历层序的节点,第一次找到在InL至InR之间的存在值与当前中序的的值相同,那么这个节点就是当前的根节点,中序值又将其分为左右两个序列,循环建树即可,实现见代码
#define _CRT_SECURE_NO_WARNINGS
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <string>
#include <vector>
#include <queue>
#include <map>
using namespace std;
const int MaxN = 36;
int n = 0;
int le[MaxN], in[MaxN];
typedef struct tnode{
int data;
struct tnode * lchild;
struct tnode * rchild;
tnode() { lchild = rchild = nullptr; }
}TNode, *PTNode;
PTNode CreateTree(int il,int ir) {
if (il > ir) return nullptr;
int leidx = 0, idx = il;
for (; leidx < n; ++leidx) {
idx = il; bool flag = false;
while (idx <= ir) {
if (le[leidx] == in[idx]) {
flag = true;
break;
}
++idx;
}
if (flag)break;
}
PTNode node = new TNode;
node->data = le[leidx];
node->lchild = CreateTree(il, idx - 1);
node->rchild = CreateTree(idx + 1, ir);
return node;
}
int pidx = 0;
void pre(PTNode root) {
if (!root)return;
cout << root->data;
if (++pidx != n)cout << " ";
pre(root->lchild);
pre(root->rchild);
}
int idx = 0;
void post(PTNode root) {
if (!root)return;
post(root->lchild);
post(root->rchild);
cout << root->data;
if (++idx != n)cout << " ";
}
int main() {
#ifdef _DEBUG
freopen("data.txt", "r+", stdin);
#endif // _DEBUG
std::ios::sync_with_stdio(false);
PTNode root;
cin >> n;
for (int i = 0; i < n; ++i)cin >> le[i];
for (int i = 0; i < n; ++i)cin >> in[i];
root = CreateTree(0, n - 1);
pre(root);
cout << endl;
post(root);
return 0;
}