Clean and tidy recursive solution, best submission of course


  • 1
    class Solution {
    private:
        void traverse(TreeNode* root, int subSum, int& sum)
        {
            if(!root->left && !root->right) { sum += subSum; return ;}
            if(root->left) traverse(root->left, 10*subSum+root->left->val, sum);
            if(root->right) traverse(root->right, 10*subSum+root->right->val, sum);
        }
    public:
        int sumNumbers(TreeNode* root) 
        {
            if(!root) return 0;
            int sum = 0;
            traverse(root, root->val, sum);    
            return sum;
        }
    };
    

Log in to reply
 

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