比较简单,就连着一起写了
路径总和 I
- 注意:一定得走到叶子才算
- 直接看代码吧,注释也就几行。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
// 递归解决战斗
public boolean hasPathSum(TreeNode root, int targetSum) {
// 递归结束条件
if(root == null){
return false;
}
// 找到结果条件
if(targetSum == root.val && root.left == null && root.right == null){
return true;
}
// 往左右继续递归
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
}
路径总和 II
- 相当于在 I 的基础上,加入了一个路径的存储、修改
- 注意。。存储的路径要 new 出来再存入
class Solution {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
find(root, targetSum);
return ans;
}
void find(TreeNode root, int targetSum){
// 递归结束条件
if(root == null){
return;
}
// 路径在递归前后进行增减
path.add(root.val);
// 找到答案的情况
if(targetSum == root.val && root.left == null && root.right == null){
ans.add(new LinkedList<>(path));
}
find(root.left, targetSum - root.val);
find(root.right, targetSum - root.val);
path.removeLast();
}
}