112. Path Sum I: 点击打开链接
/**
* Definition for a binary tree node. //判断是否有这样的路径满足和为sum
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
return helper(root,sum);
}
public boolean helper(TreeNode root,int sum){
if(root==null){
return false;
}
if(root.left==null && root.right==null){
if(root.val==sum){
return true;
}
}
return helper(root.left,sum-root.val) || helper(root.right,sum-root.val);
}
}
113. Path Sum II: 点击打开链接
/**
* Definition for a binary tree node. //写出从根节点开始的和为sum的每一条路径
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result=new ArrayList<>();
List<Integer> path=new ArrayList<>();
helper(root,sum,result,path);
return result;
}
public void helper(TreeNode root,int target,List<List<Integer>> result,List<Integer> path){
if(root==null){
return;
}
if(root.left==null && root.right==null){
if(root.val==target){
path.add(root.val);
result.add(path);
return;
}
}
if(root.left!=null){
List<Integer> left=new ArrayList<>(path); //下一层的添加在之前的基础上添加,因此deep copy
left.add(root.val);
helper(root.left,target-root.val,result,left);
}
if(root.right!=null){
List<Integer> right=new ArrayList<>(path);
right.add(root.val);
helper(root.right,target-root.val,result,right);
}
}
}
437. Path Sum III:
点击打开链接
/**
* Definition for a binary tree node. //数出从任意节点开始的和为sum的路径的条数
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int pathSum(TreeNode root, int sum) { //根节点开始的满足条件的路径和 + 左子树的情况 + 右子树的情况
if (root == null) return 0;
return helper(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
}
private int helper(TreeNode node, int sum) { //从任意node开始满足条件的路径和
if (node == null) return 0;
int left=helper(node.left, sum - node.val);
int right=helper(node.right, sum - node.val);
return (node.val == sum ? 1 : 0) +left+right;
}
}