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]
]
tag: binary tree, DFS
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ans = new ArrayList<>();
if (root == null) return ans;
dfs(root, new ArrayList<>(), ans, 0, sum);
return ans;
}
private void dfs(TreeNode root, List<Integer> temp, List<List<Integer>> ans, int path, int sum){
if (root == null) return;
temp.add(root.val);
path += root.val;
if (root.left == null && root.right == null){
//System.out.println("path: " + path + " temp: " + temp.toString());
if (path == sum){
ans.add(new ArrayList<>(temp));
}
}
dfs(root.left, temp, ans, path, sum);
dfs(root.right, temp, ans, path, sum);
temp.remove(temp.size() - 1);
path -= root.val;
}
}