0ms C Recursion solution,easy to understand.


  • 0
    W

    /**

    • Definition for a binary tree node.
    • struct TreeNode {
    • int val;
      
    • struct TreeNode *left;
      
    • struct TreeNode *right;
      
    • };
      */

    void travel(struct TreeNode* root,char* vals,int* totalSum){
    if(root == NULL) {
    return;
    }

    vals[strlen(vals)+1] = '\0';
    vals[strlen(vals)] = root->val + '0';
    
    if(root->left == NULL && root->right == NULL){
        for(int i = 0;i < strlen(vals);i++){
            *totalSum += (vals[i] - '0') * pow(10,strlen(vals) - 1 -i);
        }
        vals[strlen(vals) - 1] = '\0';
        return;
    }
    travel(root->left,vals,totalSum);
    travel(root->right,vals,totalSum);
    vals[strlen(vals)-1] = '\0';
    

    }

    int sumNumbers(struct TreeNode* root) {
    int totalSum = 0;
    char vals[10] = {0};
    travel(root,vals,&totalSum);
    return totalSum;
    }


Log in to reply
 

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