Skip to content

Latest commit

 

History

History
24 lines (22 loc) · 785 Bytes

113. 路径总和 II.md

File metadata and controls

24 lines (22 loc) · 785 Bytes
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> lists = new ArrayList<>();
        LinkedList<Integer> list = new LinkedList<>();
        pathSumDFS(root, targetSum, list, lists);
        return lists;
    }
    
    private void pathSumDFS(TreeNode root, int target, LinkedList<Integer> list, List<List<Integer>> lists) {
        if (root == null) return;
        target -= root.val;
        list.addLast(root.val);
        if (target == 0 && root.left == null && root.right == null)
            lists.add(new ArrayList<>(list));
        else {
            pathSumDFS(root.left, target, list, lists);
            pathSumDFS(root.right, target, list, lists);
        }
        list.removeLast();
    }
}