/**
* 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>> result = new LinkedList<>();
if(root == null){
return result;
}
findAllResult(root,sum,new LinkedList<>(),result);
return result;
}
void findAllResult(TreeNode root,int sum,List<Integer> cur,List<List<Integer>> result){
if(root==null){
return ;
}
//先将自己放进去
cur.add(root.val);
if(root.left==null && root.right==null && sum==root.val){
result.add(new LinkedList(cur));
//移除刚添加进去的节点
cur.remove(cur.size()-1);
return;
}
//如果不是叶子节点,则需要继续向下递归
else{
findAllResult(root.left,sum-root.val,cur,result);
findAllResult(root.right,sum-root.val,cur,result);
}
//如果左右子节点都执行完了,需要将45行中的当前节点移除,他也是最后的节点
cur.remove(cur.size()-1);
}
}
08-17