Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target
.
A valid path is from root node to any of the leaf nodes.
Example
Given a binary tree, and target = 5
:
1
/
2 4
/
2 3
return
[ [1, 2, 2], [1, 4] ]
1 /** 2 * Definition of TreeNode: 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left, right; 6 * public TreeNode(int val) { 7 * this.val = val; 8 * this.left = this.right = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 /** 14 * @param root the root of binary tree 15 * @param target an integer 16 * @return all valid paths 17 */ 18 public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) { 19 // Write your code here 20 List<List<Integer>> res = new ArrayList<List<Integer>>(); 21 if (root == null){ 22 return res; 23 } 24 List<Integer> path = new ArrayList<Integer>(); 25 helper(res, path, root, target); 26 return res; 27 } 28 29 private void helper(List<List<Integer>> res, List<Integer> path, TreeNode root, int target){ 30 if (root.left == null && root.right == null){ 31 if (root.val == target) { 32 path.add(root.val); 33 res.add(new ArrayList<Integer>(path)); 34 path.remove(path.size() - 1); 35 } 36 return; 37 } 38 path.add(root.val); 39 if (root.left != null) { 40 helper(res, path, root.left, target - root.val); 41 } 42 if (root.right != null) { 43 helper(res, path, root.right, target - root.val); 44 } 45 path.remove(path.size() - 1); 46 return; 47 } 48 }