Description
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,

tree
return
[
[5,4,11,2],
[5,8,4,5]
]
Solution
DFS
在leaf节点处就要停止递归了哦。
/**
* 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>> paths = new LinkedList<>();
pathSumRecur(root, sum, new LinkedList<>(), paths);
return paths;
}
public void pathSumRecur(TreeNode root, int sum
, List<Integer> path, List<List<Integer>> paths) {
if (root == null) {
return;
}
path.add(root.val);
if (root.left == null && root.right == null) {
if (root.val == sum) {
paths.add(new LinkedList<>(path));
}
} else {
pathSumRecur(root.left, sum - root.val, path, paths);
pathSumRecur(root.right, sum - root.val, path, paths);
}
path.remove(path.size() - 1);
}
}