UVa 548 Tree (中序遍历&后序遍历&DFS)
2013-10-28 15:08
417 查看
548 - Tree
Time limit: 3.000 secondshttp://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=104&page=show_problem&problem=489
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 associatedwith 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两步合并,详见代码。
完整代码:
/*0.086s*/ #include<cstdio> #include<algorithm> using namespace std; int in[10010], post[10010], min_sum, ans; void dfs(int n, int* in, int* post, int sum) { if (n <= 0) return; int p = find(in, in + n, post[n - 1]) - in; sum += post[n - 1]; if (n == 1) { if (sum < min_sum) { min_sum = sum; ans = post[n - 1]; } ///you should output the value of the leaf node of a path of least value. else if (sum == min_sum) ans = min(ans, post[n - 1]); ///In the case of multiple paths of least value you should pick the one with the least value on the terminal node. return; } dfs(p, in, post, sum);///左子树 dfs(n - p - 1, in + p + 1, post + p, sum);///右子树 } int main() { char ch; int n, i; while (~scanf("%d%c", &in[0], &ch)) { if (ch == 10)///只读了一个数(就换行了) { scanf("%d", &post[0]); printf("%d\n", post[0]); continue; } n = 1; while (scanf("%d%c", &in[n++], &ch), ch != 10) ; for (i = 0; i < n; ++i) scanf("%d", &post[i]); ans = min_sum = -1u >> 1; dfs(n, in, post, 0); printf("%d\n", ans); } return 0; }
相关文章推荐
- IKexpression简介
- MySQL数据库设置远程访问权限方法小结
- asynctask与handler的比较
- 一个非常好的OpenGL外文博客
- android控件属性
- 常用的选择器
- Delphi中DBChart的应用
- Java 环境变量配置
- eclipse rcp 插件快捷键设置 冲突解决方案
- 通向架构师的道路(第十八天)万能框架Spring(一)
- Unity打包WP8项目流程及经验
- war文件
- bcb平台的C++dll的静态调用法和动态调用法的方法
- C#中Lambda表达式
- 将App客户端发布到App Store中的总体思路流程
- Depth and stencils
- C系列语言终极校对宝典【第一、第二部分】
- c++ 数组,变量,指针,引用, 初始化,赋值
- jvm内存溢出解决方案
- mybatis 批量删除