Simple recursive yet accepted as best in cpp

  • 0
    class Solution {
        void traverse(TreeNode* root, vector<string>& paths, string path)
            path += to_string(root->val);
            if(!root->left && !root->right) paths.push_back(path);
            if(root->left) traverse(root->left, paths, path);
            if(root->right) traverse(root->right, paths, path);
        int sumNumbers(TreeNode* root) {
            if(!root) return 0;
            int sum = 0;
            vector<string> paths;
            string path;
            traverse(root, paths, path);
            for(auto& path: paths)
                sum += stoi(path);
            return sum;

Log in to reply

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