Leetcode 113. Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
5
/
4 8
/ /
11 13 4
/ \ /
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]

题意:是112题的followup,要求输出所有符合条件的路径。

思路:
在112题解法的框架上做一些改变。
增加一个list记录每次遍历的路径,这个list在回溯到上一个节点的时候需要把当前点从list中删除。
找到了满足条件的路径后,需要把这个路径的list加到结果集中,此时需要加一个new ArrayList,如果直接加传参的list,由于引用的性质会有bug。

public List<List<Integer>> pathSum(TreeNode root, int sum) {
    List<List<Integer>> res = new ArrayList<>();
    if (root == null) {
        return res;
    }

    dfs(root, sum, new ArrayList<>(), res);
    return res;
}

public void dfs(TreeNode root, int sum, List<Integer> list, List<List<Integer>> res) {
    list.add(root.val);
    if (root.left == null && root.right == null) {
        if (root.val == sum) {
            res.add(new ArrayList<>(list));
        }
        list.remove(list.size() - 1);
        return;
    }

    if (root.left != null) {
        dfs(root.left, sum - root.val, list, res);
    }

    if (root.right != null) {
        dfs(root.right, sum - root.val, list, res);
    }
    list.remove(list.size() - 1);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容