1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25


void sumNumbers(TreeNode *n, int num, int& sum) {
    num = num*10 + n->val;

    if (n->left == NULL & n->right == NULL) {
        sum += num;
        return;
    }

    if (n->left != NULL) {
        sumNumbers(n->left, num, sum);
    }

    if (n->right != NULL){
        sumNumbers(n->right, num, sum);
    }
}

int sumNumbers(TreeNode *root) {
    if (root == NULL) return 0;
    
    int sum = 0;
    sumNumbers(root, 0, sum);
    return sum;
}
View Program Text


Test Status