Fork me on GitHub

Sum Root to Leaf Numbers

Descrpition

https://leetcode.com/problems/sum-root-to-leaf-numbers/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int sumNumbers(TreeNode* root) {
if (root == NULL) return 0;
int ret = 0;
int currentSum = 0;
this->sumLeafNode(root, ret, currentSum);
return ret;
}

void sumLeafNode(TreeNode* root, int& ret, int& currentSum) {
if (root == NULL) return;
currentSum = currentSum * 10 + root->val;
if (root->left == NULL && root->right == NULL) ret += currentSum;
this->sumLeafNode(root->left, ret, currentSum);
this->sumLeafNode(root->right, ret, currentSum);
currentSum = currentSum / 10;
}
};