My recursive cpp code


  • 0
    C
    class Solution {
    public:
    
        vector<string> result;
        
        void dfs(TreeNode *root, string path)
        {
            if(!root->left && !root->right)
            {
                result.push_back(path);
                return;
            }
            
            if(root->left) 
            {
                ostringstream s;
                s << root->left->val;
                dfs(root->left, path + "->" + s.str());
            }
            if(root->right)
            {
                ostringstream s;
                s << root->right->val;
                dfs(root->right, path + "->" + s.str());
            }
        }
        
        vector<string> binaryTreePaths(TreeNode* root) 
        {
            if(!root) return result;
            
            ostringstream s;
            s << root->val;
            dfs(root, s.str());
            return result;
        }
    };

Log in to reply
 

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