解題思路:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
LinkedList<List<Integer>> res= new LinkedList<>();
LinkedList<Integer> path=new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
recu(root,sum);
return res;
}
void recu(TreeNode root,int tar){
if(root==null) return;
path.add(root.val);
tar=tar-root.val;
if(tar==0&&root.left==null&&root.right==null)
res.add(new LinkedList(path));
recu(root.left,tar);
recu(root.right,tar);
path.removeLast(); //Object removeLast()刪除列表中最後一個元素
}
}