题目描述
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
思路
根据后序遍历和中序遍历结果重构二叉树后进行层序遍历即可
Code
#include <bits/stdc++.h>
using namespace std;
const int N = 50;
int postorder[N], inorder[N];
map<int, int> mp;//记录中序遍历中每个节点的位置
vector<int> ans;
int n;
struct Node
{
int val;
Node *left;
Node *right;
Node(int x)
{
val = x;
left = nullptr;
right = nullptr;
}
};
Node *rec(int pl, int pr, int il, int ir)
{
if(pl > pr)
return nullptr;
Node *root = new Node(postorder[pr]);//后序遍历的最后一个点是根节点
int k = mp[postorder[pr]];//找到中序遍历根节点位置
auto left = rec(pl, pl + k - il - 1, il, k - 1);
auto right = rec(pl + k - il ,pr - 1, k + 1, ir);
root->left = left;
root->right = right;
return root;
}
Node *bulid()
{
for (int i = 1; i <= n; i++)
mp[inorder[i]] = i;
Node *root = rec(1, n, 1, n);//重建树
return root;
}
void bfs(Node *root)
{
queue<Node *> q;
q.push(root);
while(q.size())
{
Node *now = q.front();
q.pop();
if(now == nullptr)
continue;
ans.push_back(now->val);
auto left = now->left;
auto right = now->right;
q.push(left);
q.push(right);
}
return;
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
cin >> postorder[i];
for (int i = 1; i <= n; i++)
cin >> inorder[i];
Node *root = bulid();
bfs(root);
for (int i = 0; i < ans.size(); i++)
{
cout << ans[i];
if(i != ans.size() - 1)
cout << ' ';
}
cout << endl;
return 0;
}