112. 路径总和 - 力扣(LeetCode) (leetcode-cn.com)
只需要知道树的遍历方式 此题很好解决
这里用递归遍历的过程中 随时更新targetSum的值。
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root==null){ //根节点为空
return false;
}
if(root.right==null&&root.left==null) //叶节点的判断
{
return targetSum==root.val;
}
return (hasPathSum(root.left,targetSum-root.val))||(hasPathSum(root.right,targetSum-root.val));
}
}
r113. 路径总和 II - 力扣(LeetCode) (leetcode-cn.com)
那么这道题呢?和刚才有很多相似的地方 只不过现在要我们返回的是路径(一个组)而不是只是一个简单的判断。 所以我们需要搞一个数据结构去储存我们这一路上的值.
class Solution {
List<List<Integer>> res = new LinkedList<List<Integer>>();/作为结果;
Deque<Integer> path= new LinkedList<Integer>();//队列用于随时更新;
int num=0;
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
dfs(root,targetSum);
return res;
}
public void dfs(TreeNode root, int targetSum){
if(root==null){
return;
}//根节点不能为空
path.offerLast(root.val);//入队
targetSum-=root.val;
if(root.right==null&&root.left==null&&targetSum==0){
res.add(new LinkedList<Integer>(path));
}
dfs(root.right,targetSum);
dfs(root.left,targetSum);
path.pollLast();//出队
}
}
自己做的时候认为最难了解的就是最后一行的代码;为什么每次都要去掉队尾的一个值;也就是当前节点的值,其实这里是一个回溯的方法;
因为每次我们要搜索左节点和右节点 如果我们不用pollLast()除去最后一个元素 右节点的值就会受到左节点值影响,因为都是用的同一个队列; 用回溯的思想来讲,如果if条件满足 说明我这步走的正确,此刻path中的值已经被res.add(....)保存,否则此节点的值会被除去,重新回到上一个节点...继续搜索。