Question
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] ]
Solution
Traditional way, use DFS and recursion.
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>> result = new ArrayList<List<Integer>>(); 13 List<Integer> prevList = new ArrayList<Integer>(); 14 dfs(root, sum, result, prevList); 15 return result; 16 } 17 18 private void dfs(TreeNode root, int target, List<List<Integer>> result, List<Integer> prevList) { 19 if (root == null) 20 return; 21 prevList.add(root.val); 22 23 if (root.left == null && root.right == null) { 24 if (root.val == target) 25 result.add(new ArrayList<Integer>(prevList)); 26 } else { 27 List<Integer> tmpList2 = new ArrayList<Integer>(prevList); 28 if (root.left != null) 29 dfs(root.left, target - root.val, result, prevList); 30 if (root.right != null) 31 dfs(root.right, target - root.val, result, tmpList2); 32 } 33 34 } 35 }