【LeetCode】Path Sum II
2015-03-17 22:31
344 查看
题目:Path Sum II
<span style="font-size:18px;">/**LeetCode Path Sum II * 给定一棵二叉树,和一个目标值,找到值相加等于目标值的所有路径的集合 * 遍历所有路径,找到值符合的 * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } * */ package javaTrain; import java.util.ArrayList; import java.util.List; public class Train11 { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> lists = new ArrayList(); List<Integer> list = new ArrayList(); help(root,sum,lists,list); return lists; } private void help(TreeNode root,int sum,List<List<Integer>> lists,List<Integer> list){ if(root == null) return; list.add(root.val); if(root.left == null && root.right == null && root.val == sum){ List<Integer> newList = new ArrayList(list); lists.add(newList); //return 不能在这里返回,因为list中有这层的叶节点,因为还要找别的路径,所以的回溯到上一节点 } help(root.left,sum-root.val,lists,list); help(root.right,sum-root.val,lists,list); list.remove(list.size()-1); //在这,将这层节点从list中去除 } } </span>
相关文章推荐
- [Leetcode]Path Sum II
- [LeetCode] Unique Paths && Unique Paths II && Minimum Path Sum (动态规划之 Matrix DP )
- 【LeetCode with Python】 Path Sum II
- Leetcode-113. Path Sum II
- [leetcode] Path Sum II
- #leetcode#Path Sum II
- Leetcode:Path Sum II
- [leetcode]Path Sum II
- [LeetCode] Path Sum II
- LeetCode 113: Path Sum II 二叉树遍历
- leetcode — path-sum-ii
- (面试题25题)LeetCode Path Sum II
- leetcode 113. Path Sum II
- [LeetCode] Path Sum II 解题报告
- LeetCode | Path Sum II
- LeetCode_Path Sum II
- leetcode Path Sum II
- Leetcode Path Sum II
- 【LeetCode】Path Sum II
- [LeetCode] Path Sum II 深度搜索