Question
Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/
2 3
The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.
Return the sum = 12 + 13 =25.
Solution
递归遍历,到叶子节点就累加起来,然后需要用一个变量来记录路径中的值。
Code
class Solution {
public:
int sumNumbers(TreeNode *root) {
int total = 0;
string path;
sumNumbersCore(root, path, total);
return total;
}
void sumNumbersCore(TreeNode* root, string path, int& total) {
if (root != NULL) {
// int 转 char
path.push_back('0' + root->val);
if (root->left != NULL)
sumNumbersCore(root->left, path, total);
if (root->right != NULL)
sumNumbersCore(root->right, path, total);
if (root->left == NULL && root->right == NULL) {
total += stoi(path);
path.pop_back();
}
}
}
};