题目翻译:
给定二叉树的先序序列和中序序列后,需要输出后序序列第一个数字。
题解思路:
可以建树也可以不建树
代码:
不建树:
#include<bits/stdc++.h>
using namespace std;
int N, pre[50010], in[50010];
vector<int> p;
void build(int h1, int t1, int h2, int t2)
{
if (h1 > t1 || h2 > t2) return;
int i;
for (i = h2;pre[h1] != in[i];i++);
build(h1 + 1, i + h1 - h2, h2, i - 1);
build(t1 - t2 + i + 1, t1, i + 1, t2);
p.push_back(pre[h1]);
}
int main()
{
cin >> N;
for (int i = 0;i < N;i++)cin >> pre[i];
for (int i = 0;i < N;i++)cin >> in[i];
build(0, N - 1, 0, N - 1);
cout << p[0];
}
建树:
#include<bits/stdc++.h>
using namespace std;
int N, pre[50010], in[50010], tag = 0, cnt = 0;
struct node {
int l = -1, r = -1, val = 0;
}v[50010];
int build(int h1, int t1, int h2, int t2)
{
if (h1 > t1) return -1;
int root = cnt++, i;
v[root].val = pre[h1];
for (i = h2;pre[h1] != in[i];i++);
v[root].l = build(h1 + 1, i + h1 - h2, h2, i - 1);
v[root].r = build(t1 - t2 + i + 1, t1, i + 1, t2);
return root;
}
void post1(int root)
{
if (root==-1) return;
post1(v[root].l);
post1(v[root].r);
if (tag) return;
cout << v[root].val;
tag++;
}
int main()
{
cin >> N;
for (int i = 0;i < N;i++)cin >> pre[i];
for (int i = 0;i < N;i++)cin >> in[i];
int root = build(0, N - 1, 0, N - 1);
post1(root);
}
坑点:
无