方法一:DFS
    遇到问题:string使用生疏,以及在对节点node1返回上级节点时对所需数据有关node1的部分进行删除:尝试使用pop进行删除但是由于string格式形式,导致失败,于是通过看解析将每个节点对应的数据保存在函数中,在返回上一级时调用保存在函数的数据进行操作

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