4ms C++ easy to understand.


  • 0
    A
    void sumit(TreeNode* root, int &total, int &sum){
            sum += root->val;
            if(!root->left && !root->right){
                total += sum;
            }
            if(root->left){
                sum *=10;
                sumit(root->left,total,sum);
                sum /=10;
            }
            if(root->right){
                sum *= 10;
                sumit(root->right, total, sum);
                sum /=10;
            }
            
            sum -=root->val;
        }
        int sumNumbers(TreeNode* root) {
            if(!root) return 0;
            int total = 0;
            int sum =0;
            sumit(root,total,sum);
            return total;
            
        }

Log in to reply
 

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