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 binary tree 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 ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { 12 // Start typing your Java solution below 13 // DO NOT write main() function 14 ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); 15 if(root == null){ 16 return result; 17 } 18 ArrayList<Integer> seqs = new ArrayList<Integer>(); 19 int curSum = 0; 20 21 generatePathSum(root, result, seqs, curSum, sum); 22 return result; 23 } 24 25 public void generatePathSum(TreeNode root, ArrayList<ArrayList<Integer>> result, 26 ArrayList<Integer> seqs, int curSum, int expectedSum){ 27 curSum += root.val; 28 seqs.add(root.val); 29 30 boolean isLeaf = root.left == null && root.right == null; 31 if(curSum == expectedSum && isLeaf){ 32 ArrayList<Integer> tmp = new ArrayList<Integer>(); 33 tmp.addAll(seqs); 34 result.add(tmp); 35 } 36 37 if(root.left != null){ 38 generatePathSum(root.left, result, seqs, curSum, expectedSum); 39 } 40 41 if(root.right != null){ 42 generatePathSum(root.right, result, seqs, curSum, expectedSum); 43 } 44 45 seqs.remove(seqs.size() - 1); 46 47 } 48 }
refactor code:
1 public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); 5 if(root == null){ 6 return result; 7 } 8 ArrayList<Integer> seqs = new ArrayList<Integer>(); 9 int curSum = 0; 10 11 generatePathSum(root, result, seqs, curSum, sum); 12 return result; 13 } 14 15 public void generatePathSum(TreeNode root, ArrayList<ArrayList<Integer>> result, 16 ArrayList<Integer> seqs, int curSum, int expectedSum){ 17 curSum += root.val; 18 seqs.add(root.val); 19 20 boolean isLeaf = root.left == null && root.right == null; 21 if(curSum == expectedSum && isLeaf){ 22 ArrayList<Integer> tmp = new ArrayList<Integer>(); 23 tmp.addAll(seqs); 24 result.add(tmp); 25 seqs.remove(seqs.size() - 1); 26 return; 27 } 28 29 if(root.left != null){ 30 generatePathSum(root.left, result, seqs, curSum, expectedSum); 31 } 32 33 if(root.right != null){ 34 generatePathSum(root.right, result, seqs, curSum, expectedSum); 35 } 36 37 seqs.remove(seqs.size() - 1); 38 39 }