Path Sum II

描述

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 and sum = 22,

  1. 5
  2. / \
  3. 4 8
  4. / / \
  5. 11 13 4
  6. / \ / \
  7. 7 2 5 1

return

  1. [
  2. [5,4,11,2],
  3. [5,8,4,5]
  4. ]

分析

跟上一题相比,本题是求路径本身。且要求出所有结果,左子树求到了满意结果,不能return,要接着求右子树。

代码

  1. // Path Sum II
  2. // 时间复杂度O(n),空间复杂度O(logn)
  3. public class Solution {
  4. public List<List<Integer>> pathSum(TreeNode root, int sum) {
  5. List<List<Integer>> result = new ArrayList<>();
  6. ArrayList<Integer> cur = new ArrayList<>(); // 中间结果
  7. pathSum(root, sum, cur, result);
  8. return result;
  9. }
  10. private static void pathSum(TreeNode root, int gap, ArrayList<Integer> cur,
  11. List<List<Integer>> result) {
  12. if (root == null) return;
  13. cur.add(root.val);
  14. if (root.left == null && root.right == null) { // leaf
  15. if (gap == root.val)
  16. result.add(new ArrayList<>(cur));
  17. }
  18. pathSum(root.left, gap - root.val, cur, result);
  19. pathSum(root.right, gap - root.val, cur, result);
  20. cur.remove(cur.size() - 1);
  21. }
  22. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/binary-tree/recursion/path-sum-ii.html