这道题用DFS解比较好,注意吃和吐成对出现,代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
if(root == null){
return res;
}
List<Integer> path = new ArrayList<>();
helper(root, sum, path, res);
return res;
}
private void helper(TreeNode node, int sum, List<Integer> path, List<List<Integer>> res){
if(node == null){
return;
}
path.add(node.val);
// Must gurantee this is a leaf node
if(node.val == sum && node.left == null && node.right == null){
res.add(new ArrayList<>(path));
}
// Go deeper
helper(node.left, sum - node.val, path, res);
helper(node.right, sum - node.val, path, res);
// Reset the status
path.remove(path.size() - 1);
}
}