用深度优先搜索DFS,只不过数据结构相对复杂一点,需要用到二维的集合,而且每当DFS搜索到新节点时,都要保存该节点。而且每当找出一条路径之后,都将这个保存为一维集合的路径保存到最终结果二维集合中。并且,每当DFS搜索到子节点,发现不是路径和时,返回上一个结点时,需要把该节点从一维集合中移除。
递归解法
// Path Sum II
// 时间复杂度O(n),空间复杂度O(logn)
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<>();
ArrayList<Integer> cur = new ArrayList<>(); // 中间结果
pathSum(root, sum, cur, result);
return result;
}
private static void pathSum(TreeNode root, int gap, ArrayList<Integer> cur, List<List<Integer>> result) {
if (root == null) return;
cur.add(root.val);
if (root.left == null && root.right == null && gap == root.val) { // leaf
result.add(new ArrayList<>(cur));
}
pathSum(root.left, gap - root.val, cur, result);
pathSum(root.right, gap - root.val, cur, result);
cur.remove(cur.size() - 1);
}
}