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

  • 0
    void sumTree(TreeNode* root,int n, int & ans){
            n = n*10 + root->val;
            if(!root->left && !root->right){
                ans += n;
            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;
            return ans;

Log in to reply

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