给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
分析
知道中序+后序或者前序,就能确定一棵唯一的二叉树。所以此题知道后序+中序,可以建立二叉树后层序遍历。由于后序是左右根,所以最后面的节点就是根,然后在中序中找到这个根的位置,左边就是左子树的范围,右边就是右子树的范围,递归处理即可。
代码
// _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// . ' \| |// `.
// / \||| : |||// \
// / _||||| -:- |||||- \
// | | \\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
//
// .............................................
// 佛祖保佑 一发AC 永无BUG
#include <bits/stdc++.h>
#define LL long long
using namespace std;
const int maxn = 1e3 + 10;
const int inf = 0x3f3f3f3f;
const double PI = acos(-1.0);
typedef pair<int, int> PII;
int zhong[maxn], hou[maxn];
struct node {
node *l, *r;
int data;
};
int cnt1, cnt2;
int n;
node *build(int l, int r) {
if (l > r) return NULL;
node *root = new node;
root->data = hou[cnt2];
int i;
for (i = 0; i < n; i++) {
if (zhong[i] == hou[cnt2]) break;
}
cnt2--;
root->r = build(i + 1, r);
root->l = build(l, i - 1);
return root;
}
vector<int> ans;
void ceng(node *root) {
queue<node*> q;
q.push(root);
while(q.size()) {
auto now = q.front();
q.pop();
ans.push_back(now->data);
if(now->l != NULL) q.push(now->l);
if(now->r != NULL) q.push(now->r);
}
}
int main(int argc, char const *argv[]) {
cin >> n;
for (int i = 0; i < n; i++) cin >> hou[i];
for (int i = 0; i < n; i++) cin >> zhong[i];
cnt2 = n - 1;
node *root = build(0, n - 1);
ceng(root);
for(int i = 0; i < n; i++) printf("%d%c",ans[i],i == n-1 ? '\n' : ' ');
}