题目描述
输入一棵二叉树的层序和中序遍历,分别输出其前序和后序遍历
Input Specification:
第一行输入树的大小,接下来一行给出树的层序遍历,最后一行给出树的中序遍历。
Output Specification:
第一行输出其前序遍历,第二行输出其后序遍历。
Sample Input:
8
1 2 7 3 6 5 9 4
2 1 5 3 9 7 4 6
Sample Output:
1 2 7 3 5 9 6 4
2 5 9 3 4 6 7 1
解题思路
在层序遍历中找到第一个没被访问过且在对应的中序区间里的结点,那么这个结点就是当前的根结点,然后根据其在中序区间里的位置分别划分左右子树,递归建树。
测试的时候由于中序和后序复制了前序的代码,而且忘了改,导致一直调用前序遍历的部分结果,然后一直和我想的输出不同,一度怀疑是重建出了问题。。。打死也不复制代码了。。
Code
- AC代码
#include<bits/stdc++.h>
using namespace std;
vector<int> lev, in;
struct Node{
int val;
struct Node *left, *right;
Node(int _val):val(_val), left(NULL), right(NULL) {
};
};
unordered_map<int, int> m;
Node *rebuildTree(int ll, int lr, int il, int ir) {
if(il > ir) return NULL;
Node *root = NULL;
int i, j;
for(i = ll