Concise solution accepted by using c++


  • 0
    N
    ## Here's the code ##
    

    int sumNumbers(TreeNode *root) {
        int sum = 0;
    
        // if the root is empty, return 0
        if (root == NULL)
            return 0;
    
        // if a node has no children, the value of this node is added to total sum
        if (root->left == NULL && root->right == NULL)
            sum += root->val;
    
        // if a node has left child, the value of its left child
        // is updated to (root->val * 10 + root->left->val)
        if (root->left != NULL) {
            root->left->val += (root->val) * 10;
            sum += sumNumbers(root->left);
        }
    
        // if a node has right child, the value of its right child
        // is updated to (root->val * 10 + root->right->val)
        if (root->right != NULL) {
            root->right->val += (root->val) * 10;
            sum += sumNumbers(root->right);
        }
    
        return sum;
    }

Log in to reply
 

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