牛客 二叉树中和为某一值的路径 【时间19ms】【内存9560k】

https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

构造函数:new ArrayList(al)把al的所有值复制到 new ArrayList()里,并且 new ArrayList()的值不会随着al的改变而改变。

al0.addAll(al):当al的值改变,al0的值也随之改变。

Collections.copy(des,res):我一直都不知道怎么用= =

    ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
    ArrayList<Integer> path = new ArrayList<>();

    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
        dfs(root, 0, target);
        return ans;
    }

    void dfs(TreeNode r, int now, int target) {
        if (r == null) return;
        now += r.val;
        if (now > target) return;
        if (r.left == null && r.right == null && now != target) return;
        path.add(r.val);
        if (r.left == null && r.right == null && now == target) 
            ans.add(new ArrayList<>(path));
        else {
            dfs(r.left, now, target);
            dfs(r.right, now, target);
        }
        path.remove(path.size() - 1);
    }
原文地址:https://www.cnblogs.com/towerbird/p/11588353.html