Elegant c++ solution by recusion, beating 99.8% other c++ coders.


  • 0
    S
    void sumTree(TreeNode* root,int n, int & ans){
            n = n*10 + root->val;
            if(!root->left && !root->right){
                ans += n;
                return;
            }
            if(root->left)  sumTree(root->left,n,ans);
            if(root->right) sumTree(root->right,n,ans);
        }
        
        int sumNumbers(TreeNode* root) {
            int ans = 0;
            if(!root) return ans;
            sumTree(root,0,ans);
            return ans;
        }

Log in to reply
 

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