知识点:二叉树的递归遍历
这个题比较简单的,就是先建树,然后递归遍历就可以了,但是输入是比较麻烦的,我还是用我的老办法,用输入一整行,然后变成字符串流再逐个分解,还是要学习一下书上的输入方法,
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 5;
struct node {
int val;
int lchild, rchild;
} tree[N];
int tot, in[N], post[N], Hash[N], n1, n2, ans1, ans2;
int create(int inl, int inr, int postl, int postr) {
if (inl > inr) return -1;
int q = ++tot;
tree[q].val = post[postr];
int r = Hash[post[postr]];
int numleft = r - inl;
tree[q].lchild = create(inl, r - 1, postl, postl + numleft - 1);
tree[q].rchild = create(r + 1, inr, postl + numleft, postr - 1);
return q;
}
void solve(int root, int sum) {
if (root == -1) return;
if (tree[root].lchild == -1 && tree[root].rchild == -1) {
if (tree[root].val + sum < ans1) {
ans1 = tree[root].val + sum; ans2 = tree[root].val;
} else if (tree[root].val + sum == ans1 && tree[root].val < ans2) {
ans2 = tree[root].val;
}
return;
}
solve(tree[root].lchild, sum + tree[root].val);
solve(tree[root].rchild, sum + tree[root].val);
}
int main() {
string s1, s2;
while (getline(cin, s1)) {
getline(cin, s2);
tot = 0; n1 = 0; n2 = 0;
stringstream ss(s1);
string tmp;
while (ss >> tmp) {
in[n1++] = stoi(tmp);
Hash[in[n1- 1]] = n1 - 1;
}
stringstream tt(s2);
while (tt >> tmp) {
post[n2++] = stoi(tmp);
}
int root = create(0, n1 - 1, 0, n2 - 1);
ans1 = 1000000000; ans2 = -1;
solve(root, 0);
cout << ans2 << endl;
}
return 0;
}