Very simple recursion solution using c++


  • 0
    L
    int helper(TreeNode* root, int prev)
    {
        if(!root)
            return 0;
        int num = prev * 10 + (root->val);
        if(!root->left && !root->right)//if node is leaf
            return num;
        else
            return helper(root->left, num) + helper(root->right, num);
    }
    int sumNumbers(TreeNode* root) {
        return helper(root, 0);
    }

Log in to reply
 

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