当前位置: 代码迷 >> 综合 >> 二叉树所有路径
  详细解决方案

二叉树所有路径

热度:64   发布时间:2023-10-26 22:56:13.0

思路:用一个path变量保存一条路径,判断标准是否是叶子节点。注意一点vector类似于int,如果想要按地址传递参数的话,需要加&变成引用,将int转换为string用to_string()函数。

class Solution {
public:
    void allpath(TreeNode *root,string path,vector<string> &paths){
       
        if(root!=NULL){
            
             path+=to_string(root->val);
        if(root->left==NULL&&root->right==NULL){
            paths.push_back(path);
        }
        else{
            path+="->";
            allpath(root->left,path,paths);
            allpath(root->right,path,paths);
        }
        }
       
       
    }
    vector<string> binaryTreePaths(TreeNode* root) {
      vector<string> paths;
      
        if(root!=NULL){
            allpath(root,"",paths);
        }
        return paths;
    }
};

  相关解决方案