import java.util.ArrayList; import java.util.List; /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res=new ArrayList<List<Integer>>(); if(root==null) return res; List<Integer> temp=new ArrayList<Integer>(); DFS(root,sum,0,temp,res); return res; } public void DFS(TreeNode root,int sum,int total,List<Integer> temp,List<List<Integer>> res) { //将当前节点添加进去 temp.add(root.val); total+=root.val; //如果此时是已经是叶子节点 if(root.left==null&&root.right==null) { if(sum==total) { //已经找到目标路径 res.add(new ArrayList<Integer>(temp)); } return ; } if(root.left!=null) { DFS(root.left,sum,total,temp,res); temp.remove(temp.size()-1); } if(root.right!=null) { DFS(root.right,sum,total,temp,res); temp.remove(temp.size()-1); } } }