题目描述:
题目思路:
1.使用数组建树 //递归
2.理解后序遍历和中序遍历,建立左右子树
3.dfs深度搜索找出权重最小的路径
#include <iostream> #include <string> #include <sstream> #include <algorithm> using namespace std; const int maxv = 10000 + 10; int in_order[maxv], post_order[maxv], lch[maxv], rch[maxv]; int i; bool readlist(int* t){ //读入输入 string line; if(!getline(cin,line)) return false ; stringstream ss(line); i = 0; int x; while(ss >> x) t[i++] = x; return i > 0 ; } int buildtree(int L1, int R1, int L2, int R2){//将读入的两行建树 if(L1 > R1) return 0; // 空树 int root = post_order[R2] ;//后序遍历最后一个 int p = L1; while(in_order[p] != root) p++; int cnt = p-L1; // 左子树的结点个数 lch[root] = buildtree(L1, p-1, L2, L2+cnt-1); rch[root] = buildtree(p+1, R1, L2+cnt, R2-1); return root ; } int best, best_sum; // 目前为止的最优解和对应的权和 void dfs(int u, int sum){//深度搜索 sum += u; if(!lch[u] && !rch[u]) { // 叶子 if(sum < best_sum || (sum == best_sum && u < best)) { best = u; best_sum = sum; } } if(lch[u]) dfs(lch[u], sum); if(rch[u]) dfs(rch[u], sum); } int main(int argc, char *argv[]) { while(readlist(in_order)) { readlist(post_order); buildtree(0, i-1, 0, i-1); best_sum = 1000000000; dfs(post_order[i-1], 0); cout << best << " "; } return 0; }