Simple C++ recursive solution

  • 1

    class Solution {

        void dfs(TreeNode* node, int &res, int cur)
            if(!node) return; //if it is an empty node, return
            cur = cur*10+root->val; // update the current value from root to the current node 
            if(!node->left && !node->right)
            {  //if it is a leaf node
                res +=cur; //update the result
            dfs(node->left,  res, cur); // recursively process the left subtree
            dfs(node->right, res, cur);// recursively process the right subtree
        int sumNumbers(TreeNode* root) {
            int res=0;
            dfs(root, res, 0);
            return res;

Log in to reply

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