376
来源:互联网 发布:网络赢钱游戏 编辑:程序博客网 时间:2024/04/28 00:43
2017.9.28
先用递归的办法找到所有的根节点到叶子节点的路径。
再一一计算和。
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */public class Solution { /* * @param root: the root of binary tree * @param target: An integer * @return: all valid paths */ public List<List<Integer>> pathToLeaf(TreeNode root){List<List<Integer>> res = new LinkedList<>();if(root == null){return res;}if(root.left == null && root.right == null){List<Integer> tmp = new LinkedList<Integer>();tmp.add(root.val);res.add(tmp);return res;}if(root.left != null){List<List<Integer>> resLeft = pathToLeaf(root.left);for(List<Integer> list: resLeft){List<Integer> tmp = new LinkedList<Integer>();tmp.add(root.val);tmp.addAll(list);res.add(tmp);}}if(root.right != null){List<List<Integer>> resRight = pathToLeaf(root.right);for(List<Integer> list: resRight){List<Integer> tmp = new LinkedList<Integer>();tmp.add(root.val);tmp.addAll(list);res.add(tmp);}}return res;}public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) { // write your code hereList<List<Integer>> res = new LinkedList<>();if(root == null){return res;}List<List<Integer>> path = pathToLeaf(root);for(List<Integer> list : path){ //System.out.println(list);int sum = 0;for(Integer num : list){sum = sum + num;}if(sum == target){res.add(list);}}return res; }}
阅读全文
0 0
- 376
- ocp-376
- 100001 devided by 376
- cf /376/C
- Problem - 376B - Codeforces
- cf 376C
- 376 Wiggle Subsequence
- OpenXML 成为 ECMA标准 376
- 【LEETCODE】376- Wiggle Subsequence [Python]
- Codeforces Round #376 (Div. 2)
- Codeforces Round #376 (Div. 2)
- Codeforces Round #376 (Div. 2)
- Codeforces Round #376 (Div. 2)
- Codeforces Round #376A (div2)
- Codeforces contest 376&375 recordings
- 【小阅读^大脑袋】0618 NO.376
- nyoj 376 小强的Linux
- Code forces 376 C Divisible by Seven
- 多张图片上传服务器
- [线段树]HDU 4942——Game on S♂play
- 第五周项目2——建立链栈算法库
- python自学(1)-安装环境及工具、学习教程资料的准备
- 容器扩展点:后置处理器BeanPostProcessor
- 376
- input=file 通过Ajax上传
- Redis理解
- [日推荐]『拉勾招聘』手机APP可以卸掉啦!
- 手机联网状态
- 3S基础知识:GIS中的坐标系定义与转换
- ATLANT——全球房地产区域链平台
- Android 6.0以后权限申请问题
- Deep Learning(一):CNN经典网络模型摘要--AlexNet、ZFnet、GoogleNet、VGG、ResNet