Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:Given the below binary tree andsum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ] 这个是上题path-sum的进阶版,更复杂了,但是还是用DFS,只不过数据结构用的复杂了,每当DFS搜索新节点的时候就保存此节点,每当找到一条新路径就添加到list中。并且,每当DFS搜索到子节点的时候,发现不是路径和,就返回到上一节点,并把该节点从路径中删除。递归实现 import java.util.*; public class Solution { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { ArrayList<Integer> list = new ArrayList<Integer>(); paths(root, sum, list); return res; } private void paths(TreeNode root, int sum, ArrayList<Integer> list){ if(root == null) return; if(root.left == null && root.right == null && sum - root.val == 0){ list.add(root.val); res.add(new ArrayList<Integer>(list)); list.remove(list.size() - 1); return; } list.add(root.val); paths(root.left, sum - root.val, list); paths(root.right, sum - root.val, list); list.remove(list.size() - 1); } }