# DFS solution accepted with 8ms

• 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;
};``````

• 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

• This post is deleted!

• 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 );
}

};``````

• ``````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;
}``````

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