做本题之前可以先做一下 二叉树中和为某一值的路径(一)。
深度优先遍历+回溯
1、首先,深度优点遍历来说,先写上一个回溯 if (root== null) { return false; },这表示递归至最深层开始回溯。2、每次进入函数时,将 sum 减去当前节点的权重(root.val),当 sum 减到零时,说明目标路径存在,另外我们的目标是到叶子节点停止,叶子节点的条件是 root.left == null && root.right == null,所以说当 root.left == null && root.right == null && sum== 0同时满足才符合条件 ,返回 true 表示找到目标路径。(root.left == null && root.right == null 没有这两个是不算的)
3、dfs分支:对于当前节点 root有两个分支,这两个分支都有可能成为目标路径,所以深度优先遍历的写法为 return dfs(curNode.left, target) || dfs(curNode.right, target);
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
public boolean hasPathSum (TreeNode root, int sum) {
// write code here
if(root==null){
return false;
}
return dfs(root,sum);
}
public boolean dfs (TreeNode root, int sum){
if(root==null) return false;
sum-=root.val;
if(sum==0&&root.left==null&&root.right==null){
return true;
}
return dfs(root.left,sum)||dfs(root.right,sum);
}
}
深度优先遍历+回溯
思路和上面差不多,也是将 sum 减去当前节点的权重(root.val),当 sum 减到零时,说明目标路径存在,然后输出结果。只是需要用一个集合装起来。代码如下:
这里说两个点。
if(root==null) return res;1.这里为什么返回res?
我们可能会觉得是返回null,但是本题的直接返回null是不行的。有个特例不能过。题目要求返回[],我们不能直接返回null。假设我们在走一条不符合题意的路线,就假设我们的最左边的路线不符合题意吧,我们按照代码的逻辑,一直往下走,我们会发现if中有个条件expectNumber==0,但是我们这条路径肯定不符合条件,所以if语句不会执行,所以我们知道res是空的,返回即可。而且这个语句是我们递归的终止条件。这里也可以用return newArrayList<ArrayList<Integer>>();
stack.pop();2.这是什么用?
这里的作用就是回溯,假设我们在走一条不符合题意的路线,就假设我们的最左边的路线不符合题意吧,我们按照代码的逻辑,一直往下走,最后return res(此时res为空),然后我们需要回溯,就需要将stack中的元素pop出来,实现回溯的目的。
import java.util.*;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
Stack<Integer> stack=new Stack<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int expectNumber){
if(root==null) return res;
stack.push(root.val);
expectNumber-=root.val;
if(expectNumber==0&&root.left==null&&root.right==null){
res.add(new ArrayList<Integer>(stack));
}
FindPath(root.left,expectNumber);
FindPath(root.right,expectNumber);
stack.pop();
return res;
}
}

京公网安备 11010502036488号