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]
]
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root the root of binary tree
* @param target an integer
* @return all valid paths
*/
public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
// Write your code here
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (root == null){
return res;
}
List<Integer> path = new ArrayList<Integer>();
helper(res, path, root, target);
return res;
} private void helper(List<List<Integer>> res, List<Integer> path, TreeNode root, int target){
if (root.left == null && root.right == null){
if (root.val == target) {
path.add(root.val);
res.add(new ArrayList<Integer>(path));
path.remove(path.size() - 1);
}
return;
}
path.add(root.val);
if (root.left != null) {
helper(res, path, root.left, target - root.val);
}
if (root.right != null) {
helper(res, path, root.right, target - root.val);
}
path.remove(path.size() - 1);
return;
}
}