一.題目
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
.
二.解題技巧
三.實現代碼
#include <iostream>
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
void sumNumbers(TreeNode*root, int &Result, int &TmpResult)
{
if (!root)
{
return;
}
// update the TmpResult
TmpResult = TmpResult * 10 + root->val;
if (!root->left && !root->right)
{
Result += TmpResult;
}
if (root->left)
{
sumNumbers(root->left, Result, TmpResult);
}
if (root->right)
{
sumNumbers(root->right, Result, TmpResult);
}
// restore the TmpResult;
TmpResult = (TmpResult - root->val) / 10;
}
public:
int sumNumbers(TreeNode* root)
{
int Result = 0;
int TmpResult = 0;
sumNumbers(root, Result, TmpResult);
return Result;
}
};