C++ 6ms recursive solution


  • 0
    I
    void printPaths(TreeNode* root,string path,vector<string>& result){
            if(!root){
                
                    result.push_back(path);
                
                return;
            }
            path+=to_string(root->val);
            //cout<<path<<endl;
            if(root->left == NULL && root->right == NULL){
                result.push_back(path);
            }
            if(root->left){
                printPaths(root->left,path+"->",result);
            }
            if(root->right)
                printPaths(root->right,path+="->",result);
        }
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> result;
            if(!root)
                return result;
            string tmp="";
            printPaths(root,tmp,result);
            return result;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.