Cattle off the path of a binary tree and the time value of 19ms [] [] memory 9560k

 

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

 

Constructor: new ArrayList (al) to copy all of the values ​​al to new ArrayList () in, and new ArrayList () values ​​do not change with the change al.

al0.addAll (al): when changing the value of al, the value al0 also changed.

Collections.copy (des, res): I never know how to use = =

 

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

 

Guess you like

Origin www.cnblogs.com/towerbird/p/11588353.html