Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
都是用dfs解决,不同的是112只要求判断是否存在path sum,113要求返回所有可能的path sum。
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null ) return false;
return hasPath(root, sum);
}
public boolean hasPath(TreeNode root, int sum){
if(root.left == null && root.right == null && root.val == sum) return true; //叶子节点
if(root.left != null && hasPath(root.left,sum-root.val))return true;
if(root.right != null && hasPath(root.right,sum-root.val))return true;
return false;
}
}
public class Solution {
List<List<Integer>> r = new ArrayList<List<Integer>>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if(root == null ) return r;
List<Integer> tmp = new ArrayList<Integer>();
hasPath(root, sum,tmp);
return r;
}
public void hasPath(TreeNode root, int sum , List<Integer> tmp){
if(root.left == null && root.right == null && root.val == sum) { //叶子节点
tmp.add(root.val);
r.add(new ArrayList<Integer>(tmp));
tmp.remove(tmp.size()-1);
return;
};
tmp.add(root.val); //dfs
if(root.left != null){
hasPath(root.left, sum-root.val , tmp);
}
if(root.right != null){
hasPath(root.right, sum-root.val , tmp);
}
tmp.remove(tmp.size()-1);
}
}