C++ recursive 4ms


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

  • 0
    C

    void binTreePath(TreeNode* root, string p, vector<string>& res)
    {
    if (!root)enter code here
    {
    return;
    }
    if (!root->left && !root->right)
    {
    char t[10];
    sprintf_s(t, "%d", root->val);
    p.append(t);
    res.push_back(p);
    return;
    }
    char t[12];
    sprintf_s(t, "%d->", root->val);
    p.append(t);
    binTreePath(root->left, p, res);
    binTreePath(root->right, p, res);
    }


Log in to reply
 

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