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
.
1:获得每一个根到叶节点的路径;2:计算路径所代表的值;3:获得所有值的和
int sumNumbers(TreeNode *root)
{
if(root == NULL)
{
return 0;
}
if(!root->left && !root->right)
{
return root->val;
}
int value = 0;
vector<int> temp;
sumNumbersCore(root, value, temp);
return value;
}
void sumNumbersCore(TreeNode *root, int &value, vector<int> &temp)
{
temp.push_back(root->val);
if(root->left == NULL && root->right == NULL)
{
int curValue = 0;
for(int i = 0; i < (int)temp.size(); i++)
{
curValue = curValue * 10 + temp[i];
}
value += curValue;
}
if(root->left)
{
sumNumbersCore(root->left, value, temp);
}
if(root->right)
{
sumNumbersCore(root->right, value, temp);
}
temp.pop_back();
}