c++

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

java

import java.util.*;



public class Solution {

    public int ans = 0;
    public int sumNumbers (TreeNode root) {
        bfs(root,0);
        return ans;
    }
    public int bfs(TreeNode root,int add)
    {
        if(root==null){return ans;}
        if(root.left==null && root.right == null)
        {
            add=add*10;
            add=add+root.val;
            ans=ans+add;
            return ans;
        }
        if(root.left!=null)
        {
            bfs(root.left,add*10+root.val);
        }
        if(root.right!=null)
        {
            bfs(root.right,add*10+root.val);
        }
        return ans;
    }
}

python

class Solution:
    def sumNumbers(self , root ):
        def bfs(root,ans):
            if not root:
                return 0
            ans = ans*10+root.val
            if not root.left and not root.right:
                return ans
            return bfs(root.left,ans)+bfs(root.right,ans)
        return bfs(root,0)