image.png

思路:回溯

  • cur_path 记录当前路径中的总和,如果在叶子节点上出现了cur_sum == target_sum,就将cur_path放到fit_path当中。否则就进行回溯操作。
  • 回溯的“回”如何实现?cur_path.pop_back()
  • image.png

代码:

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. vector<vector<int>> fit_path;
  15. vector<int> cur_path;
  16. void traceBack(TreeNode* root, int pre_sum, int targetSum) {
  17. if (!root) {
  18. return;
  19. }
  20. int cur_sum = pre_sum + root->val;
  21. cur_path.push_back(root->val);
  22. if (!root->left && !root->right) {
  23. if (cur_sum == targetSum) {
  24. fit_path.push_back(cur_path);
  25. }
  26. }
  27. traceBack(root->left, cur_sum, targetSum);
  28. traceBack(root->right, cur_sum, targetSum);
  29. // 回溯的“回”操作
  30. cur_path.pop_back();
  31. }
  32. vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
  33. traceBack(root, 0, targetSum);
  34. return fit_path;
  35. }
  36. };