4ms cpp solution


  • 0
    P
    class Solution {
        void Add_array(TreeNode* root,int current,int &sum){ /*current = the value from top to the current node*/
            if(root->left==NULL && root->right==NULL){/*sum is the total sum of root-to-leaf numbers*/
                sum += current;
                return;
            }
            if(root->left) Add_array(root->left,current*10+root->left->val,sum);
            if(root->right) Add_array(root->right,current*10+root->right->val,sum);
            return;
        }
    public:
        int sumNumbers(TreeNode* root) {
            if(!root) return 0;
            int sum = 0;
            Add_array(root,root->val,sum);
            return sum;
        }
    };

  • 0
    A

    @PKUGoodSpeed All recursive solutions use extra space, in fact, all recursive soltuions use A LOT of extra space in thread stack.


  • 0
    P

    @ayuanx Yea, I see. I wrote this solution long time ago. If not using recursive, we must use stack for traversal the tree (I think this must to be done in this problem.).


Log in to reply
 

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