My stoi code. Most simple to understand


  • 0
    H
    int sumNumbers(TreeNode* root) {
            sum = 0;
            if(root)
                sumTree(root, "");
            else
                return 0;
            return sum;   
        }
        void sumTree(TreeNode* root, string prev){
            if(root->right == NULL && root->left == NULL){
                string::size_type sz;
                prev += to_string(root->val);
                int i_dec = stoi (prev,&sz);
                sum+=i_dec;
                return;
            }
            if(root->left)
                sumTree(root->left, prev+to_string(root->val));
            if(root->right)    
                sumTree(root->right, prev+to_string(root->val));
        }

Log in to reply
 

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