题目大意
假设二叉树中的所有键都是不同的正整数。唯一的二叉树可以由给定的一对后序和中序遍历序列确定。它是按级别顺序打印数字的简单标准例程。但是,如果你认为问题太简单,那你就太天真了。这次你应该以“锯齿形顺序”打印数字——也就是说,从根开始,逐级打印数字,从左到右和从右到左交替。
解题思路
- 首先根据二叉树的中序遍历和后序遍历获得重建以后的二叉树
- 然后对重建的二叉树进行和层次遍历
- 需要注意的是这里使用的是之字形遍历
代码
#include<bits/stdc++.h>
using namespace std;
int num;
vector<int> inorder, postorder, ans;
map<int, int> inmap, postmap;
struct TreeNode{
int val = 0;
TreeNode* left = nullptr;
TreeNode* right = nullptr;
};
TreeNode* bulitTree(int inleft,int inright,int postleft,int postright) {
if (postleft>postright) {
return nullptr;
}
TreeNode* root = new TreeNode();
root->val = postorder[postright];
int index = inmap[postorder[postright]];//根结点所在的中序遍历的位置
root->left = bulitTree(inleft, index - 1, postleft, postleft + index - inleft - 1);
root->right = bulitTree(index + 1, inright, postleft + index - inleft, postright - 1);
return root;
}
void visitLayer(TreeNode* root) {
queue<TreeNode*> que;
stack<int> sta;
int lay = 0;
if (root != nullptr) {
que.push(root);
}
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; i++) {
TreeNode* tem = que.front();
que.pop();
if (tem->left != nullptr) {
que.push(tem->left);
}
if (tem->right != nullptr) {
que.push(tem->right);
}
if (lay % 2 == 1) {//奇数层,不用反向
ans.push_back(tem->val);
}
else {//利用栈反向
sta.push(tem->val);
}
}
if (lay % 2 == 0) {
while (!sta.empty()) {
int x = sta.top();
sta.pop();
ans.push_back(x);
}
}
lay++;
}
}
int main() {
cin >> num;
int tem;
for (int i = 0; i < num; i++) {
cin >> tem;
inorder.push_back(tem);
inmap.emplace(tem, i);
}
for (int i = 0; i < num; i++) {
cin >> tem;
postorder.push_back(tem);
postmap.emplace(tem, i);
}
TreeNode* root = new TreeNode();
root = bulitTree(0, num - 1, 0, num - 1);//获得了二叉树的根结点
visitLayer(root);
for (int i = 0; i < ans.size(); i++) {
if (i == ans.size() - 1) {
cout << ans[i] << endl;
}
else {
cout << ans[i] << ' ';
}
}
return 0;
}