根节点到叶子节点的节点值之和等于\ sum sum
二叉树根节点到叶子节点和为指定值的路径
https://www.nowcoder.com/practice/840dd2dc4fbd4b2199cd48f2dadf930a?tpId=117&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey
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); }