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. class Solution {
  4. public:
  5. vector<vector<int> > pathSum(TreeNode *root, int sum) {
  6. vector<vector<int> > result;
  7. vector<int> cur; // 中间结果
  8. pathSum(root, sum, cur, result);
  9. return result;
  10. }
  11. private:
  12. void pathSum(TreeNode *root, int gap, vector<int> &cur,
  13. vector<vector<int> > &result) {
  14. if (root == nullptr) return;
  15. cur.push_back(root->val);
  16. if (root->left == nullptr && root->right == nullptr) { // leaf
  17. if (gap == root->val)
  18. result.push_back(cur);
  19. }
  20. pathSum(root->left, gap - root->val, cur, result);
  21. pathSum(root->right, gap - root->val, cur, result);
  22. cur.pop_back();
  23. }
  24. };

相关题目

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