DFS solution accepted with 8ms


  • 2
    H

    Code is concise:

    class Solution {
    public:
        void dfs(TreeNode *root, int prefix) {
            if (root == NULL) return;
            if (root -> left == NULL && root -> right == NULL) { ans += prefix * 10 + root -> val; return; }
            if (root -> left != NULL) dfs(root -> left, prefix * 10 + root -> val);
            if (root -> right != NULL) dfs(root -> right, prefix * 10 + root -> val);
        }
        int sumNumbers(TreeNode *root) {
            ans = 0;
            dfs(root, 0);
            return ans;
        }
    private:
        int ans;
    };

  • 0
    S

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example


  • 0
    Z
    This post is deleted!

  • 1
    Z

    A little redundancy,maybe you can derect set a value in the function sumNumbers like this

    class Solution {
    public:
        int sumNumbers(TreeNode *root,int x = 0) {
            if( root == NULL )  return 0;
            x = x * 10 + root -> val;
            if( root -> left == NULL && root -> right == NULL ) return x;
            return sumNumbers( root -> left,x ) + sumNumbers( root -> right,x );
        }
        
    };

  • 1
    H
    int sumNumbers(TreeNode *root) {
        if(!root)return 0;
        if(!root->left && !root->right)
    	{
    		return root->val;
    	}
    	int sum=0;
    	if(root->left)
    	{
    	    root->left->val+=root->val*10;
    		sum+=sumNumbers(root->left);
    	}
    	if(root->right)
    	{
    	    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.