3ms C solution (very easy to understand)


  • 0
    A
    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
      * };
     */
    
    int sumNumbersRecursive(struct TreeNode *node , int currentNum, int totalSum ) {
    
        if( node == NULL ){
            return totalSum; 
        }
        
        if(node->left == NULL && node->right == NULL){
            totalSum = totalSum  + currentNum*10 + node->val;
            return totalSum;
        }
        
        totalSum  = sumNumbersRecursive(node->left ,currentNum*10 + node->val, totalSum) ;
        totalSum = sumNumbersRecursive(node->right,currentNum*10 + node->val , totalSum) ;
        
        return totalSum;
    }
    
    int sumNumbers(struct TreeNode *root) {
        
        struct TreeNode * node = root; 
        int totalSum = 0 ;
        if( node == NULL ){
            return totalSum; 
        }
        totalSum = sumNumbersRecursive(root, 0 , 0);
        return totalSum;    
      
    }

Log in to reply
 

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