/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { //定义结果集 res 和 保存路径的集合 path List<List<Integer>> res = new ArrayList<>(); LinkedList<Integer> path = new LinkedList<>(); public List<List<Integer>> pathSum(TreeNode root, int sum) { recur(root,sum); return res ; } void recur(TreeNode root,int tar){ if(root == null) return; path.add(root.val); tar = tar - root.val; //如果当前节点已经是叶节点 并且 当前路径和 为目标值,返回这一条路径 if(root.left == null && root.right == null && tar == 0){ res.add(new ArrayList(path)); } //递归调用左右子树 recur(root.left,tar); recur(root.right,tar); path.removeLast(); } }