给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
立个flag,要把树的大多经典题型全部写出来,努力!!!
这道题给定中序遍历和后序遍历还原一颗二叉树,然后用层次遍历遍历整棵树。事实上,只要给定你中序遍历(提供左右子树,很关键),和任意遍历顺序(仅提供根节点)就可还原一颗二叉树,然后怎么样遍历就看题目要求了,对遍历有点迷茫的话可以看看我这篇文章(链接)
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int post[35], in[35];
vector<int> mytree;
struct binary_tree{
int data;
binary_tree* left;
binary_tree* right;
};
typedef binary_tree* tree;
tree create(int postL, int postR, int inL, int inR){
if(postL > postR){
return NULL;
}
tree root = new binary_tree;
root->data = post[postR];
int k, numleft;
for(k = inL; k <= inR; k++){
if(in[k] == post[postR]){
break;
}
}
numleft = k - inL;
root->left = create(postL, postL+numleft-1, inL, k-1);
root->right = create(postL+numleft, postR-1, k+1, inR);
return root;
}
void layer(tree root){
queue<tree> q;
q.push(root);
while(!q.empty()){
tree now = new binary_tree;
now = q.front();
q.pop();
mytree.push_back(now->data);
if(now->left != NULL) q.push(now->left);
if(now->right != NULL) q.push(now->right);
}
}
int main(){
int n, i;
cin >> n;
for(i = 1; i <= n; i++){
cin >> post[i];
}
for(i = 1; i <= n; i++){
cin >> in[i];
}
tree root = create(1, n, 1, n);
layer(root);
cout << mytree[0];
for(i = 1; i < mytree.size(); i++){
cout << " " << mytree[i];
}
}
其实要注意的是,也是我踩过的坑,在下列代码中,每次我们要准确的确定每个序列的左子树的区间和右子树的区间(建议画图,避免出错)
root->left = create(postL, postL+numleft-1, inL, k-1);
root->right = create(postL+numleft, postR-1, k+1, inR);
完成!!!(天梯赛25分到手)
下一个博客:判断一棵树是否是完全二叉树(maybe)
再见,我们下次见!!!
猛兽总是独行,只有牛羊才成群结队。
做好自己就行了!!!