Path Sum II ---LeetCode

来源:互联网 发布:李荣浩后羿知乎 编辑:程序博客网 时间:2024/04/30 23:50

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);        }    }}
0 0
原创粉丝点击