您的位置:首页 > 其它

Path Sum II ---LeetCode

2016-11-28 12:21 218 查看
https://leetcode.com/problems/path-sum-ii/

解题思路:

Path Sum 类似,都是通过递归来找到合适的叶子节点,只是这道题在过程中要记录下满足要求的所有节点。

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new ArrayList<>();

if (root == null) return result;
list.add(root.val);
helper(root, sum - root.val, list, result);

return result;
}
public void helper(TreeNode root, int sum, List<Integer> list, List<List<Integer>> result) {
if (root == null) return ;
if (root.left == null && root.right == null && sum == 0) {
result.add(new ArrayList<Integer>(list));
return ;
}
if (root.left != null) {
list.add(root.left.val);
helper(root.left, sum - root.left.val, list, result);
list.remove(list.size() - 1);
}
if (root.right != null) {
list.add(root.right.val);
helper(root.right, sum - root.right.val, list, result);
list.remove(list.size() - 1);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: