一、题目内容
二、题解
解法1:
思路
定义ans、path(LinkedList)
先序遍历,每次将根的值加入path,判断是否为叶子节点并且target减为0,true则加入ans
否则继续先序遍历左右,遍历完成后移除当前节点回溯
代码
public class Solution {private ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();private LinkedList<Integer> path = new LinkedList<>();public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) {// write code hererecur(root, sum);return ans;}public void recur(TreeNode root, int target){if (root == null) {return;}path.add(root.val);target -= root.val;if (target == 0 && root.left == null && root.right == null) {ans.add(new ArrayList<>(path));}recur(root.left, target);recur(root.right, target);path.removeLast();}}

