C++ 3ms


  • 0

    Use string to record the path.

    class Solution {
        void getPath(vector<string>& pathVec, TreeNode* root, string& tmpPath) {
            if(root == nullptr) return;
            if(root->left == nullptr && root->right == nullptr) {
                tmpPath += to_string(root->val);
                pathVec.push_back(tmpPath);
                tmpPath.pop_back();
                return ;
            }
    
            tmpPath += to_string(root->val);
            if(root->left)
                getPath(pathVec, root->left, tmpPath);
    
            if(root->right)
                getPath(pathVec, root->right, tmpPath);
                
            tmpPath.pop_back();
        }
    public:
        int sumNumbers(TreeNode* root) {
            if(root == nullptr) return 0;
            vector<string> pathVec;
            string tmpPath = "";
            getPath(pathVec, root, tmpPath);
            int retVal = 0;
            for(auto s: pathVec) {
                retVal += stoi(s);
            }
    
            return retVal;
        }
    };
    

Log in to reply
 

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