My c solution 2 ms


  • 1
    B
    int dfs(struct TreeNode* root, int num) {
        if (root == NULL) return 0; // if only one child node is NULL, do not count it
        if (root->left == NULL && root->right == NULL) return num * 10 + root->val; // if the node is leaf node, return the sum value
        return dfs(root->left, num * 10 + root->val) + dfs(root->right, num * 10 + root->val);
    }
    
    int sumNumbers(struct TreeNode* root) {
        return dfs(root, 0);
    }

  • 0
    R

    same idea,same language.

    int sumNumbersRecursive(struct TreeNode* root,int preval) {
    	if(NULL==root->left && NULL==root->right){
    		return preval*10+root->val;
    	}
    	int ret=0;
    	preval=preval*10+root->val;
    	if(NULL!=root->left){
    		ret+= sumNumbersRecursive(root->left,preval);
    	}
    	if(NULL!=root->right){
    		ret+= sumNumbersRecursive(root->right,preval);
    	}
    
    	return ret;
    }
    
    int sumNumbers(struct TreeNode* root) {
    	if(NULL==root) return 0;
        
    	return sumNumbersRecursive(root,0);
    }

Log in to reply
 

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