C++ recursive solution


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

Log in to reply
 

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