Path Sum II
来源:互联网 发布:淘宝小白帽 编辑:程序博客网 时间:2024/05/19 00:17
1.题目
给定一棵树和数sum,求所有根到子叶中和为sum的路径
2.算法
我们需要数据结构来维护中间路径结果以及保存满足条件的所有路径
某博客大神代码
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if(root==null) return res; ArrayList<Integer> item = new ArrayList<Integer>(); item.add(root.val); helper(root,sum-root.val,item,res); return res; } private void helper(TreeNode root, int sum, ArrayList<Integer> item, ArrayList<ArrayList<Integer>> res) { if(root == null) return; if(root.left==null && root.right==null && sum==0) { res.add(new ArrayList<Integer>(item)); return; } if(root.left!=null) { item.add(root.left.val); helper(root.left,sum-root.left.val,item,res); item.remove(item.size()-1); } if(root.right!=null) { item.add(root.right.val); helper(root.right,sum-root.right.val,item,res); item.remove(item.size()-1); } }
0 0
- LeetCode: Path Sum II
- LeetCode Path Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- Path Sum II
- [LeetCode] Path Sum II
- 【leetcode】Path Sum II
- [113]Path Sum II
- Path Sum II
- Path Sum II
- [LeetCode]Path Sum II
- Path Sum II
- Path Sum II
- [Leetcode]Path Sum II
- [leetcode]Path Sum II
- Path Sum II
- Leetcode: Path Sum II
- Path Sum II
- Template Template Parameters(双重模板参数)
- Spring和SpringMVC父子容器关系初窥
- Android studio 点击按钮跳转到新的Activity
- 每天一个linux命令(9):touch 命令
- idea中properties配置文件中显示utf-8编码时,怎么办?
- Path Sum II
- java 处理高并发(转载)
- 解决powerdesigner连接mysql时连接不上的问题
- Java 遍历List ConcurrentModificationException 异常解析
- 【poj 2151】Check the difficulty of problems 概率dp
- express不是内部命令或者外部命令
- session、cookie与“记住我的登录状态”的功能的实现
- Swift3.0带来的变化汇总系列一——字符串与基本运算符中的变化
- 检查服务器是否支持ipv6