Short 4ms C++ solution with recursion


  • 0
    D
    class Solution {
    public:
        int sumNumbersHelper(TreeNode* t, int num) {
            num = num * 10 + t->val;
            if (!t->left && !t->right) { 
                return num;
            } else if (t->left && t->right) {
                return sumNumbersHelper(t->left, num) + sumNumbersHelper(t->right, num);    
            } else {
                return sumNumbersHelper(t->left ? t->left : t->right, num);
            }
        }
        
        int sumNumbers(TreeNode* root) {
            return root? sumNumbersHelper(root, 0) : 0;    
        }
    };

Log in to reply
 

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