leetcode 113. 路径总和 II【回溯】

深度优先搜索结合回溯的思路可以解决本题。
定义一个List来存放搜索路径上的节点值,当搜索到达某个叶子节点且路径总和满足题目要求时,将该路径对应的List放入记录答案的List中,并回溯;如此递归下去,直到所有路径都被遍历一次。

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

    private void dfs(TreeNode x, int sum, int curSum, List<Integer> paths){
        paths.add(x.val);
        curSum += x.val;
        if(x.left == null && x.right == null){
            if(curSum == sum){
                res.add(new ArrayList<>(paths));
            }
            paths.remove(paths.size() - 1);
            return;
        }
        if(x.left != null)
            dfs(x.left, sum, curSum, paths);
        if(x.right != null)
            dfs(x.right, sum, curSum, paths);
        paths.remove(paths.size() - 1);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值