https://leetcode-cn.com/problems/path-sum/submissions/
// 遍历顺序:中左右
// 每遍历一个,记录一个作为路径,并把总和算出来
// 需要递归和回溯、
// 先尝试写出所有路径的递归、回溯算法
// 函数参数:(结点值, 单条路径, 目标和) 返回(void)
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null) return false;
List<Integer> path = new ArrayList<>();
List<Integer> sum_arr = new ArrayList<>();
traverser(root, path, sum_arr);
for(Integer i : sum_arr){
if(i == targetSum) return true;
}
return false;
}
public void traverser(TreeNode root, List<Integer> path, List<Integer> sum_arr){
path.add(root.val);//先添加中间结点
//如果到底,那就直接添加path的总和到path_arr
if(root.left == null && root.right == null){
int sum = 0;
for(int i = 0; i < path.size(); i++){
sum += path.get(i);
}
sum_arr.add(sum);
}
//如果没到底,那就继续遍历,先左后右
if(root.left != null){
traverser(root.left, path, sum_arr);
path.remove(path.size() - 1);//回溯
}
if(root.right != null){
traverser(root.right, path, sum_arr);
path.remove(path.size() - 1);
}
}
}
改进之后:
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null) return false;
List<Integer> path = new ArrayList<>();
List<Integer> sum_arr = new ArrayList<>();
return traverser(root, path, sum_arr, targetSum);
}
public boolean traverser(TreeNode root, List<Integer> path, List<Integer> sum_arr, int targetSum){
path.add(root.val);//先添加中间结点
//如果到底,那就直接添加path的总和到path_arr
if(root.left == null && root.right == null){
int sum = 0;
for(int i = 0; i < path.size(); i++){
sum += path.get(i);
}
System.out.println("sum = " + sum);
if(sum == targetSum) return true;
}
//如果没到底,那就继续遍历,先左后右
if(root.left != null){
if(traverser(root.left, path, sum_arr, targetSum)) return true;//只有if才能过,因为直接用return traverser的话,会使得肯定有返回值,后面一句就肯定不会执行。
path.remove(path.size() - 1);//回溯
}
if(root.right != null){
if(traverser(root.right, path, sum_arr, targetSum)) return true;
path.remove(path.size() - 1);
}
return false;
}
}
答案的方法更简单,就是不用记录路径,每递归一层,就把那个结点的数值减掉。当然我也想到了,但是很难设计出这样的递归代码,而且又涉及到回溯
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null) return false;
return f(root, targetSum - root.val);
}
public boolean f(TreeNode root, int count){
//终止条件 遇到叶子节点,就返回
if(root.left == null && root.right == null && count == 0) return true;
if(root.left == null && root.right == null && count != 0) return false;
//递归
if(root.left != null){
count -= root.left.val;
if(f(root.left, count) == true) return true;
count += root.left.val;//回溯
}
if(root.right != null){
count -= root.right.val;
if(f(root.right, count) == true) return true;
count += root.right.val;//回溯
}
return false;
}
}