Given a binary tree containing digits from 0-9
only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3
which represents the number 123
.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path 1->2
represents the number 12
.
The root-to-leaf path 1->3
represents the number 13
.
Return the sum = 12 + 13 = 25
.
思路:这也是一道DFS题。遍历节点时,分为2类:第一类是当前节点为null,第二类是叶子节点,allSum加上从根节点到叶子节点的和。
class Solution {
public:
void sumNumbersHelper(TreeNode* root, int sum, int &allSum) {
if (root == NULL) {
allSum += sum;
return;
}
if ((root->left == NULL && root->right == NULL)) {
allSum += root->val;
allSum += sum*10;
return;
}
if(root->left != NULL) {
sumNumbersHelper(root->left, sum*10+root->val, allSum);
}
if (root->right != NULL) {
sumNumbersHelper(root->right, sum*10+root->val, allSum);
}
}
int sumNumbers(TreeNode *root) {
int allSum = 0;
sumNumbersHelper(root, 0, allSum);
return allSum;
}
};