方法一:深度遍历(DFS)—自身对深度遍历还有认识不足需要进一步加强
    首先通过遍历得到是否存在叶节点的路径长度等于所给的目标长度,在前序遍历中我们将所经历的节点都记录到path中,若最后的路径长度等于目标路径长度则将path压入结果,最后(也是自己没有想到的一部分)通过后序遍历将前序遍历所等到的path进行依次弹出,尝试压入新的路径节点,重复上述操作

    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>> pathSum(TreeNode* root, int targetSum) {
    15. dfs(root,targetSum);
    16. return result;
    17. }
    18. void dfs(TreeNode* root, int targetSum){
    19. if(root==NULL){
    20. return;
    21. }
    22. path.emplace_back(root->val);
    23. if(!root->left&&!root->right&&root->val==targetSum){
    24. result.emplace_back(path);
    25. }
    26. dfs(root->left,targetSum-root->val);
    27. dfs(root->right,targetSum-root->val);
    28. path.pop_back();
    29. }
    30. vector<int>path;
    31. vector<vector<int>>result;
    32. };

    方法2:使用unordered_map哈希表记录每个节点的父节点,使用反转函数reverse()

    1. class Solution {
    2. public:
    3. vector<vector<int>>result;
    4. unordered_map<TreeNode*,TreeNode*>parent;
    5. void getpath(TreeNode* root){
    6. vector<int>temp;
    7. while(root!=NULL){
    8. temp.emplace_back(root->val);
    9. root=parent[root];
    10. }
    11. reverse(temp.begin(),temp.end());
    12. result.emplace_back(temp);
    13. }
    14. vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
    15. if(root==NULL){
    16. return result;
    17. }
    18. queue<TreeNode*>s;
    19. queue<int>v;
    20. v.emplace(root->val);
    21. s.emplace(root);
    22. while(!s.empty()){
    23. TreeNode* head=s.front();
    24. s.pop();
    25. int temp=v.front();
    26. v.pop();
    27. if(head->left!=NULL){
    28. s.emplace(head->left);
    29. v.emplace(temp+head->left->val);
    30. parent[head->left]=head;
    31. }
    32. if(head->right!=NULL){
    33. s.emplace(head->right);
    34. v.emplace(temp+head->right->val);
    35. parent[head->right]=head;
    36. }
    37. if(head->right==NULL&&head->left==NULL&&temp==targetSum){
    38. getpath(head);
    39. }
    40. }
    41. return result;
    42. }
    43. };