Simple recursive solution


  • 0
        void sum(TreeNode* t, int cur, int& res) {
            if (!t) return;
            cur = 10 * cur + t->val;
            if (t->left) sum(t->left, cur, res);
            if (t->right) sum(t->right, cur, res);
            else if (!t->left) res += cur;
        }
    
        int sumNumbers(TreeNode* root) {
            int res = 0;
            sum(root, 0, res);
            return res;
        }
    

Log in to reply
 

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