34. 二叉树中和为某一值的门路
思路:先序遍历
存一个数到path中,target就减一次
留神: 把一条门路path增加到最终返回的res中时,须要新创建一个LinkedList对象,不然前面path变动,res中也会跟着变动。
代码:
LinkedList<List<Integer>> res = new LinkedList<>();//最终寄存的所有门路LinkedList<Integer> path = new LinkedList<>();//一条门路public List<List<Integer>> pathSum(TreeNode root, int sum) { recur(root, sum); return res;}void recur(TreeNode root, int tar) { if (root == null) return;//是null 就阐明到底了 path.add(root.val);//把节点增加到path中 tar = tar - root.val;//target同步减去root的值 if (tar == 0 && root.left == null && root.right == null) { res.add(new LinkedList(path));//如果到底了且target也减完了,这条门路才符合条件 //能够存入res中,这里留神要新建一个LinkedList对象 } recur(root.left, tar);//先序遍历 左右子树 recur(root.right, tar); path.removeLast();//如果以后节点的左右都遍历完了,返回上一节点}