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();//如果当前节点的左右都遍历完了,返回上一节点
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。