112,113,114. Path Sum I && II & III
Path Sum I
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.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
class Solution { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) return false; if (root.left == null && root.right == null && root.val == sum) return true; return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); } }
Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<List<Integer>> pathSum(TreeNode root, int sum) { 12 List<List<Integer>> all = new ArrayList<>(); 13 helper(root, new ArrayList<Integer>(), all, 0, sum); 14 return all; 15 } 16 17 private void helper(TreeNode root, List<Integer> list, List<List<Integer>> all, int currSum, int sum) { 18 // exit condition 19 if (root == null) return; 20 21 list.add(root.val); 22 currSum += root.val; 23 24 if (currSum == sum && root.left == null && root.right == null) { 25 all.add(new ArrayList<Integer>(list)); 26 } 27 28 helper(root.left, list, all, currSum, sum); 29 helper(root.right, list, all, currSum, sum); 30 list.remove(list.size() - 1); 31 } 32 }
Path Sum III
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1 Return 3. The paths that sum to 8 are: 1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11
1 public class Solution { 2 public int pathSum(TreeNode root, int sum) { 3 int[] arr = new int[1]; 4 preOrder(root, sum, arr); 5 return arr[0]; 6 } 7 8 public void preOrder(TreeNode root, int sum, int[] count) { 9 if (root == null) return; 10 printSums(root, sum, 0, count); 11 preOrder(root.left, sum, count); 12 preOrder(root.right, sum, count); 13 } 14 15 public void printSums(TreeNode root, int sum, int currentSum, int[] count) { 16 if (root == null) return; 17 currentSum += root.val; 18 if (currentSum == sum) { 19 count[0]++; 20 } 21 printSums(root.left, sum, currentSum, count); 22 printSums(root.right, sum, currentSum, count); 23 } 24 }