题意
假设二叉树里面的数字都是正数且各不相同,给先序和中序遍历, 要输出后序遍历的第一个元素
思路
- 先序和中序遍历序列可以唯一确定一颗二叉树,我们可以建树之后后序遍历就好
代码
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
struct node {
int val;
struct node* left;
struct node* right;
node(int x): val(x), left(NULL), right(NULL){}
};
unordered_map<int, int> lookup;
node* build_tree(vector<int>& in_order, int inL, int inR, vector<int>& pre_order, int preL, int preR) {
if(inL > inR) {
return NULL;
}
node *root = new node(pre_order[preL]);
int pos = lookup[root->val];
int num_left = pos - inL;
root->left = build_tree(in_order, inL, pos - 1, pre_order, preL + 1, preL + num_left);
root->right = build_tree(in_order, pos + 1, inR, pre_order, preL + num_left + 1, preR);
return root;
}
void post_travel(node* cur, vector<int>& post_order) {
if(cur) {
post_travel(cur->left, post_order);
post_travel(cur->right, post_order);
post_order.emplace_back(cur->val);
}
}
int main() {
vector<int> pre_order, in_order;
int N;
scanf("%d", &N);
pre_order.resize(N);
in_order.resize(N);
for(int i = 0; i < N; i++) scanf("%d", &pre_order[i]);
for(int i = 0; i < N; i++) {
scanf("%d", &in_order[i]);
lookup[in_order[i]] = i;
}
node* root = build_tree(in_order, 0, N - 1, pre_order, 0, N - 1);
vector<int> post_order;
post_travel(root, post_order);
cout << post_order.front();
return 0;
}