给一颗点带权的二叉树的中序遍历和后序遍历,找一个叶子使其到根的路径上的权和最小,输出。
先还原树,再深度优先求值。
#include<iostream>
#include<sstream>
#include<algorithm>
using namespace std;
int len;
int inOdr[10086], postOdr[10086];
int lch[5043], rch[5043], mins,bestr;
bool read_list(int *a) {
string line;
if (!getline(cin, line)) return false;
stringstream ss(line);
int x;
len = 0;
while (ss >> x) a[len++] = x;
return true;
}
void dfs(int root,int sum) {//找到最优的叶子
sum += root;
if (lch[root]) dfs(lch[root],sum);
if (rch[root]) dfs(rch[root],sum);
if (!lch[root] && !rch[root]){//叶子
if (sum < mins || (sum == mins && root < bestr)) {
mins = sum;
bestr = root;
}
}
}
int build(int l1, int r1, int l2, int r2) {//l1 l2是中序 l2 r3后序
if (l1 > r1) return 0;
int mid=l1;
int root = postOdr[r2];
while (inOdr[mid] != root) mid++;
int temp = mid - l1;//左子树个数
lch[root] = build(l1, mid - 1, l2, l2 + temp - 1);
rch[root] = build(mid + 1, r1, l2 + temp, r2 - 1);
return root;
}
/*
3 2 1 4 5 7 6
3 1 2 5 6 7 4
7 8 11 3 5 16 12 18
8 3 11 7 16 18 12 5
*/
int main() {
while (read_list(inOdr)) {
bestr = -1; mins = 999999;
int root;
read_list(postOdr);
root = build(0, len - 1, 0, len - 1);
rch[9] = 0; lch[9] = 0;
dfs(root,0);
cout << bestr << endl;
}
return 0;
}