4ms c++ recursive method with easy-understanding structure


  • 0
    Y
    class Solution
    {
    public:
        vector<string> binaryTreePaths(TreeNode* root)
        {
            vector<string> ret;
            vector<int> c;
            if(root==nullptr)
                return ret;
            helper(root,ret,c);
            return ret;
        }
    private:
        void helper(TreeNode *root,vector<string> &ret,vector<int> &nums)
        {
            nums.push_back(root->val);
            if(root->left==nullptr && root->right==nullptr)
            {
                ret.push_back(arrayToString(nums));
                nums.pop_back();
                return;
            }
            else if(root->left && root->right==nullptr)
            {
                helper(root->left,ret,nums);
                nums.pop_back();
            }
            else if(root->right && root->left==nullptr)
            {
                helper(root->right,ret,nums);
                nums.pop_back();
            }
            else
            {
                helper(root->left,ret,nums);
                helper(root->right,ret,nums);
                nums.pop_back();
            }
        }
        string arrayToString(const vector<int> &res)
        {
            string ret;
            if(res.empty())
                return ret;
            ret+=to_string(res[0]);
            for(int i=1;i<res.size();++i)
                ret+=("->"+to_string(res[i]));
            return ret;
        }
    };

Log in to reply
 

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