Path Sum
Last updated
Last updated
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return sum == root.val;
}
return hasPathSum(root.left, sum - root.val) ||
hasPathSum(root.right, sum - root.val);
}
}class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
helper(res, new ArrayList<>(), root, sum);
return res;
}
public static void helper(List<List<Integer>> res, List<Integer> list, TreeNode root, int sum) {
if (root == null) {
return;
}
list.add(root.val);
if (root.left == null && root.right == null) {
if (sum - root.val == 0) {
res.add(new ArrayList<Integer>(list));
}
}
helper(res, list, root.left, sum - root.val);
helper(res, list, root.right, sum - root.val);
list.remove(list.size() - 1);
}
}public class Solution {
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> solution = new ArrayList<Integer>();
findSum(rst, solution, root, sum);
return rst;
}
private void findSum(ArrayList<ArrayList<Integer>> result,
ArrayList<Integer> solution, TreeNode root, int sum){
if (root == null) {
return;
}
sum -= root.val;
if (root.left == null && root.right == null) {
if (sum == 0){
solution.add(root.val);
result.add(new ArrayList<Integer>(solution));
solution.remove(solution.size()-1);
}
return;
}
solution.add(root.val);
findSum(result, solution, root.left, sum);
findSum(result, solution, root.right, sum);
solution.remove(solution.size()-1);
}
}