给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
#include <iostream>
#include<queue>
using namespace std;
int n;
typedef struct stree *Tree;
struct stree {//链二叉树
int value;
Tree left;
Tree right;
};
int data1[31], data2[31];//data1是中序,data2是后序
Tree creat() {
Tree s = (Tree)malloc(sizeof(stree));
if (s) {
s->left = s->right = NULL;
return s;
}
else {
cout << "内存分配失败" << endl;
return NULL;
}
}
Tree tran(int s1, int e1, int s2, int e2) {
Tree s = creat();
s->value = data2[e2];//后序的最后一个节点为树的根
int rootindex = 0;
for (int i = e1; i >= s1; i--) {
if (data1[i] == data2[e2]) {
rootindex = i;//找到根在中序里的下标,可划分左右子树
break;
}
}
if (rootindex != s1) {
s->left = tran(s1, rootindex - 1, s2, s2 + rootindex - 1 - s1);
}
if (rootindex != e1) {
s->right = tran(rootindex + 1, e1, s2 + rootindex - s1, e2-1);
}
return s;
}
void seq(Tree s) {
queue<Tree> q;
q.push(s);//入列
int i = 0;
while (!q.empty()) {
Tree t = q.front();
q.pop();
cout << t->value;
if (++i != n) {
cout << " ";
}
if (t->left != NULL) {
q.push(t->left);
}
if (t->right != NULL) {
q.push(t->right);
}
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {//由题目可知,先输入后序再输入中序
cin >> data2[i];
}
for (int i = 0; i < n; i++) {
cin >> data1[i];
}
Tree s = tran(0, n - 1, 0, n - 1);
seq(s);
return 0;
}