已知后序和中序输出前序(二叉树)
已知后序和中序输出前序(二叉树)
给出二叉树的后序遍历和中序遍历,要求输出二叉树的前序遍历:
后序:2 3 1 5 7 6 4
中序:1 2 3 4 5 6 7
分析:由后序遍历的特性可知,后序的最后一个总是根结点,令root_index_in
在中序中找到该根结点,则root_index_in
把中序分为两部分,左边是左子树,右边是右子树。因为是输出前序(根左右),所以先打印出当前根结点,然后打印左子树,再打印右子树。左子树在后序中的根结点为root_index_post - (in_end - root_index_in) - 1
,即为当前根结点 - (右子树的结点树) - 1;左子树在中序中的起始索引为in_start
,末尾索引为root_index_in - 1
。右子树的根节点为当前根节点的前一个结点,即为root_index_post - 1
;右子树的起始索引为root_index_in + 1
,末尾索引为in_end
。
以下代码为输出层序遍历,将level.emplace(tree_index, root)
改为cout << root " "
即可输出前序遍历
#include <iostream>
#include <map>
using namespace std;
int post_order[30] = {0};
int in_order[30] = {0};
map<int, int> level;
int n;
inline void dfs(int root_index_post, int in_start, int in_end, int tree_index)
{
if (in_start > in_end)
return;
int root = post_order[root_index_post];
level.emplace(tree_index, root);
int root_index_in = 0;
while (in_order[root_index_in] != root)
root_index_in++;
dfs(root_index_post - in_end + root_index_in - 1, in_start, root_index_in - 1, 2 * tree_index);
dfs(root_index_post - 1, root_index_in + 1, in_end, 2 * tree_index + 1);
return;
}
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
cin >> post_order[i];
for (int i = 0; i < n; i++)
cin >> in_order[i];
dfs(n - 1, 0, n - 1, 1);
int count = 0;
for (auto it = level.begin(); it != level.end(); it++)
{
count++;
if (count != n)
cout << it->second << " ";
else
cout << it->second << endl;
}
return 0;
}