public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) { // write code here ArrayList<Integer> list = new ArrayList<>(); ArrayList<ArrayList<Integer>> lists = new ArrayList<>(); dfs(lists,list,0,sum,root); return lists; } private void dfs(ArrayList<ArrayList<Integer>> lists, ArrayList<Integer> list, int sum ,int k,TreeNode root){ if(root==null) return; sum += root.val; list.add(root.val); if(root.left==null && root.right==null){ if(sum==k){ ArrayList<Integer> gg = new ArrayList<>(); for(int l:list){ gg.add(l); } //*注意list里面嵌入list的时候 改变里面的list会改变外层list 即添加进去的是引用* lists.add(gg); } list.remove(list.size()-1); return; } dfs(lists,list,sum,k,root.left); dfs(lists,list,sum,k,root.right); list.remove(list.size()-1); }