Path Sum II
来源:互联网 发布:2017金英杰免费网络课 编辑:程序博客网 时间:2024/04/30 19:46
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:Given the below binary tree and
sum = 22
,5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5]]
Have you met this question in a real interview
思路:之前有一道PathSumd的题目,这个和之前的那个是一个思路,但是这里要把正确的路径保存到List集合中,所以稍微复杂点。深度递归,不断添加,到叶子节点的时候再不断删除添加的节点即可(不管这个路径是否满足sum,都要再删除的,满足的要找新的路径,不满足的也要找新的路径)。注意: pathList.remove(pathList.size()-1);这句不能放在叶子节点那里,必须放在最后,即遍历完左右子树,移除当前节点。
代码如下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { List<List<Integer>> resultList = new ArrayList<List<Integer>>(); public List<List<Integer>> pathSum(TreeNode root, int sum) { sumDfs(root,sum, new ArrayList<Integer>(),0); return resultList; } public void sumDfs(TreeNode root,int sum,List<Integer> pathList,int cur){ if(root==null){ return; }else{ cur = cur+root.val; pathList.add(root.val); if( root.right==null && root.left==null&&cur==sum ){ ArrayList<Integer> list = new ArrayList(pathList); resultList.add(list); } } sumDfs(root.left,sum,pathList,cur); sumDfs(root.right,sum,pathList,cur); pathList.remove(pathList.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
- PostgreSQL Concurrency with MVCC
- 说说mysql索引
- 记录 在表中 第几次出现
- 做一个好的项目经理
- HDU 3501 Calculation 2 (欧拉函数)
- Path Sum II
- 各种拟合,一元、多元、对数、指数、单峰、自定义拟合
- hdoj2031十进制转为任意进制
- AFNetworking、MKNetworkKit和ASIHTTPRequest对比
- hd1232 畅通工程
- LeetCode题解——Remove Element
- Java集合之Stack 源码分析
- 正则<1>
- firefox中 checkbox属性checked="checked"已有,但复选框却不显示打钩的原因