[leetcode] 113. 路径总和 II

113. 路径总和 II

这题跟上个题的区别112. 路径总和,需要保存下路径,且有可能出现多条路径。

在前一个题的基础上加上回溯即可

class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> ansList = new ArrayList<>();
        if (root == null) return ansList;
        List<Integer> curList = new ArrayList<>();

        findPath(root, sum, curList, ansList);

        return ansList;
    }

    private void findPath(TreeNode root, int sum, List<Integer> curList, List<List<Integer>> ansList) {
        if (root == null) return;
        curList.add(root.val);
        if (root.left == null && root.right == null && sum == root.val) {
            List<Integer> tmp = new ArrayList<>(curList);
            ansList.add(tmp);
        } else {
            findPath(root.left, sum - root.val, curList, ansList);
            findPath(root.right, sum - root.val, curList, ansList);
        }
        curList.remove(curList.size() - 1);
    }
}

posted @ 2018-11-06 21:27  ACBingo  阅读(226)  评论(0编辑  收藏  举报