Short C++ Solution~


  • 0
    T
    class Solution {
    public:
        void helper(TreeNode* root, int &sum, int cur) {
            if (!root->left && !root->right) {
                sum += cur*10 + root->val;
                return ;
            }
            if (root->left)     helper(root->left, sum, cur*10 + root->val);
            if (root->right)    helper(root->right, sum, cur*10 + root->val);
        }
        int sumNumbers(TreeNode* root) {
            int sum = 0;
            if (!root) return 0;
            if (!root->left && !root->right) return root->val;
            helper(root, sum, 0);
            return sum;
        }
    };
    

Log in to reply
 

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