题目描述
输入一棵二叉树的层序和中序遍历,分别输出其前序和后序遍历
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; i<=lr; i++) {
if(m[lev[i]] == 1) continue;
bool flag = false;
for(j = il; j<=ir; j++) {
if(lev[i] == in[j]) {
flag = true;
break;
}
}
if(flag) {
m[lev[i]] = 1;
root = new Node(lev[i]);
root->left = rebuildTree(ll, lr, il, j-1);
root->right = rebuildTree(ll, lr, j+1, ir);
break;
}
}
return root;
}
void preOrderT(Node *root) {
if(!root) return ;
cout << root->val << " ";
preOrderT(root->left);
preOrderT(root->right);
}
void inOrderT(Node *root) {
if(!root) return ;
inOrderT(root->left);
cout << root->val << " ";
inOrderT(root->right);
}
void postOrderT(Node *root) {
if(!root) return ;
postOrderT(root->left);
postOrderT(root->right);
cout << root->val << " ";
}
void bfs(Node *root) {
queue<Node*> q;
q.push(root);
int curL = 1, nextL = 0;
while(!q.empty()) {
Node *cur = q.front();
q.pop();
curL--;
cout << cur->val << " ";
if(cur->left) {
q.push(cur->left);
nextL++;
}
if(cur->right) {
q.push(cur->right);
nextL++;
}
if(!curL) {
curL = nextL;
nextL = 0;
cout << '\n';
}
}
}
int main() {
freopen("in.txt", "r", stdin);
int N;
cin >> N;
lev.resize(N);
in.resize(N);
for(int i = 0; i<N; i++) {
cin >> lev[i];
}
for(int i = 0; i<N; i++) {
cin >> in[i];
}
Node *root = rebuildTree(0, N-1, 0, N-1);
preOrderT(root);
cout << '\n';
inOrderT(root);
cout << '\n';
postOrderT(root);
cout << '\n';
bfs(root);
return 0;
}