import java.util.ArrayList; /** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { ArrayList<ArrayList<Integer>> paths =new ArrayList<>(); public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) { findPath(root,target,0,new ArrayList<>()); return paths; } public void findPath(TreeNode cur,int target,int sum,ArrayList<Integer> path){ //剪枝,当前和已大于目标和时直接返回 if(cur == null || sum >= target){ return; } //走过该节点,所以添加到路径中,并加上该节点的值 path.add(cur.val); sum+=cur.val; //判断是否是叶子节点,是则判断是否满足和,否则不做操作 if(cur.left == null && cur.right == null){ if(target == sum){ ArrayList<Integer> tmp =new ArrayList<>(); for(int i =0 ;i<path.size();i++){ tmp.add(path.get(i)); } paths.add(tmp); } } //遍历左节点 if(cur.left != null){ findPath(cur.left,target,sum,path); } //遍历右节点 if(cur.right != null){ findPath(cur.right,target,sum,path); } //和减去该节点的值,路径上去掉该节点 sum-=cur.val; path.remove(path.size()-1); } }
原文:https://www.cnblogs.com/MoonBeautiful/p/13055937.html