【二叉树】已知后序与中序求先序
思想
后序最后一个结点位置为root
中序第一个结点位置为start
最后一个结点位置为end
先序顺序为根左右
后序最后结点一定为整棵树的根结点
在中序中找到该根结点位置i
位置i
左面为左子树 位置i
右面为右子树
左子树的根结点在后序的位置为最后位置根结点root
减去右子树的所有结点end-i+1
即root+i-end-1
左子树第一个结点位置为start
最后一个结点位置为i-1
右子树第一个结点位置为i+1
最后一个位置为end
首先先输出根结点即post[root]
接着递归左子树 递归右子树
最终输出即为先序
代码
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
vector<int> post, in, pre;
void pre_order(int root, int start, int end){
if (start > end) return;
int i = start;
while (i < end && in[i] != post[root]) i++;
pre.push_back(post[root]);
pre_order(root+i-end-1, start, i-1);
pre_order(root-1, i+1, end);
}
int main(){
int n, node;
scanf("%d", &n);
for (int i = 0; i < n; i++){
scanf("%d", &node);
post.push_back(node);
}
for (int i = 0; i < n; i++){
scanf("%d", &node);
in.push_back(node);
}
pre_order(n-1, 0, n-1);
printf("%d", pre[0]);
for (int i = 1; i < n; i++)
printf(" %d", pre[i]);
return 0;
}