C++ 4ms recoursive solution


  • 2
    P
    vector<string> binaryTreePaths(TreeNode* root) 
    {
        vector<string> result;
        binaryTreePaths(root, "", result) ;
        return result;    
    }
    
    void binaryTreePaths(TreeNode* root, string path, vector<string> & result) 
    {
        if(!root)
            return;
            
        if(!root->left && !root->right)
        {
            result.push_back(path + to_string(root->val));
            return;
        }
        
        string node_path = path + to_string(root->val) + "->";
        binaryTreePaths(root->left, node_path, result);
        binaryTreePaths(root->right, node_path, result);
    }

Log in to reply
 

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