Binary Tree Path Sum
LintCode-376. Binary Tree Path Sum
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) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
List<Integer> pathList = new ArrayList<>();
pathList.add(root.val);
pathSumHelper(root, target, result, pathList, root.val);
return result;
}
void pathSumHelper(TreeNode node, int target, List<List<Integer>> result, List<Integer> pathList, int sum) {
if (node.left == null && node.right == null) {
if (sum == target) {
result.add(new ArrayList<Integer>(pathList));
}
return;
}
if (node.left != null) {
pathList.add(node.left.val);
pathSumHelper(node.left, target, result, pathList, sum + node.left.val);
pathList.remove(pathList.size() - 1);
}
if (node.right != null) {
pathList.add(node.right.val);
pathSumHelper(node.right, target, result, pathList, sum + node.right.val);
pathList.remove(pathList.size() - 1);
}
}
}
Hope this helps,
Michael