Tree
You are to determine the value of the leaf node in a given binary tree that is the terminal node of a path of least value from the root of the binary tree to any leaf. The value of a path is the sum of values of nodes along that path.
Input
The input file will contain a description of the binary tree given as the inorder and postorder traversal sequences of that tree. Your program will read two line (until end of file) from the input file. The first line will contain the sequence of values associated with an inorder traversal of the tree and the second line will contain the sequence of values associated with a postorder traversal of the tree. All values will be different, greater than zero and less than 10000. You may assume that no binary tree will have more than 10000 nodes or less than 1 node.
Output
For each tree description you should output the value of the leaf node of a path of least value. In the case of multiple paths of least value you should pick the one with the least value on the terminal node.
Sample Input
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
255
255
Sample Output
1
3
255
题意:给你一个二叉树的中序遍历和后序遍历,每一个点的序号就是这个点的权值,请求出从根节点到叶子节点权值和最小的那个节点,如果有多个,则输出叶子节点最小的.
分析:这道题很水,根据中序遍历和后序遍历可以很容易地建立一棵树,然后dfs一边就可以了。
至于怎么建树呢?后序遍历的最后一个点就是根节点,在中序遍历中找到这个位置,然后左边就是左子树的中序遍历,右边就是右子树的中序遍历,递归一下就能解决问题.
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <queue> #include <string> #include <sstream> using namespace std; const int maxn = 10010,inf = 0x7ffffff; int in[maxn], post[maxn], tot,l[maxn],r[maxn],res,ans = inf; bool read1() { string s; if (!getline(cin, s)) return false; stringstream ss(s); tot = 0; int x; while (ss >> x) in[tot++] = x; return tot > 0; } void read2() { string s; if (!getline(cin, s)) return; stringstream ss(s); tot = 0; int x; while (ss >> x) post[tot++] = x; } int build(int l1, int r1, int l2, int r2) { if (l1 > r1) return 0; int root = post[r2]; int o = l1; while (in[o] != root) o++; int cnt = o - l1; l[root] = build(l1, o - 1, l2, l2 + cnt - 1); r[root] = build(o + 1, r1, l2 + cnt, r2 - 1); return root; } void dfs(int u, int sum) { if (!l[u] && !r[u]) { if (sum < ans || (sum == ans && u < res)) { res = u; ans = sum; } } if (l[u]) dfs(l[u], sum + l[u]); if (r[u]) dfs(r[u], sum + r[u]); } int main() { while (read1()) { read2(); build(0, tot - 1, 0, tot - 1); ans = inf; dfs(post[tot - 1], post[tot - 1]); printf("%d ", res); } return 0; }