首页 > 其他 > 详细

[leetcode] 113. 路径总和 II

时间:2018-11-06 21:55:02      阅读:158      评论:0      收藏:0      [点我收藏+]

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);
    }
}

[leetcode] 113. 路径总和 II

原文:https://www.cnblogs.com/acbingo/p/9918325.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!