Tree
来源:互联网 发布:淘宝店宝贝描述 编辑:程序博客网 时间:2024/03/29 08:43
Description
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 63 1 2 5 6 7 47 8 11 3 5 16 12 188 3 11 7 16 18 12 5255255
Sample Output
13255
通过这道题我学会了如何通过两种深搜的序列来建立一棵二叉树。
后序遍历最后一个是根结点,然后中序遍历就可以分成左右子树,再找到左右子树的根,递归下去,就可以建立一棵二叉树了。用lch【i】和rch【i】来表示i的左右子树的根结点(即i的左右子结点)。最后按照dfs来计算权值。代码如下:
#include<cstdio>#include<string>#include<sstream>#include<iostream>using namespace std;const int maxn=10000+5;int med[maxn],fin[maxn],lch[maxn],rch[maxn];int n;bool read_line(int *a){string s;if(!getline(cin,s)) return false;int x;n=0;stringstream ss(s);while(ss>>x) a[n++]=x;return n>0;}int build_tree(int L1,int R1,int L2,int R2){if(L1>R1) return 0;int root=fin[R2],p=L1;while(root!=med[p]) p++;int cnt=p-L1;lch[root]=build_tree(L1,p-1,L2,L2+cnt-1);rch[root]=build_tree(p+1,R1,L2+cnt,R2-1);return root;}int add_node,node;void dfs(int root,int sum){sum+=root;if(!lch[root]&&!rch[root]){if(sum<add_node||(sum==add_node&&root<node)){add_node=sum;node=root;}}if(lch[root]) dfs(lch[root],sum);if(rch[root]) dfs(rch[root],sum);}int main(){while(read_line(med)){read_line(fin);build_tree(0,n-1,0,n-1);add_node=1000000000;dfs(fin[n-1],0);printf("%d\n",node);}return 0;}
这道题又用到一种读入函数:getline(cin,s),它可以读入一行到s,遇到回车停止。包含在头文件<string>里.
0 0
- Tree
- tree
- tree
- TREE
- Tree
- Tree
- tree
- tree
- tree
- tree
- tree
- tree
- Tree
- Tree
- tree
- TREE
- tree
- tree
- lnmp环境配置
- C++中的单例模式
- NSThread,NSInvocationOperation,NSBlockOperation,GCD解析
- MAC系统txt中文乱码解决办法~~~
- 模板的写法,写一个titleBar
- Tree
- 三层交换机连接路由器
- 自定义UIAlertView可以容纳多个按钮
- 架构师---名称介绍
- C/C++指针常量和常量指针
- Comet HTTP服务器推送框架之icomet
- Android控制自身应用设置实现多语言
- BZOJ 1191 超级英雄hero(二分图匹配,匈牙利算法)
- MySQL字符编码:如何从utf8升级到utf8mb4