剑指 Offer 34. 二叉树中和为某一值的路径

剑指 Offer 34. 二叉树中和为某一值的路径

回溯

这里有个注意事项,pathList 类型,需要显示回溯,如 path.remove(path.size() - 1);。而 target 作为 int 类型不需要显示回溯,因为是不可变类型,类似的还有 String

这里不可变类型指的是:当变量作为形参传递给一个函数,在该函数内部修改了这个变量,回到主函数,如果该变量的值没有发生改变,则认为是不可变类型

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();

    public List<List<Integer>> pathSum(TreeNode root, int target) {
        backtrack(root, target);
        return res;
    }

    void backtrack(TreeNode root, int target){
        if(root == null) return;

        path.add(root.val);
        target -= root.val;
        if(root.left == null && root.right == null && target == 0){
            res.add(new ArrayList<>(path));
        }
        
        backtrack(root.left, target);
        backtrack(root.right, target);
        path.remove(path.size() - 1);
    }
}

你可能感兴趣的:(#,剑指offer,算法)