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.
思路:
先序遍历的思想(根左右)+数字求和(每一层都是上层和*10+当前值)
class Solution
{
public:
int sumNumbers(TreeNode* root)
{
int sum = 0;
if (root==NULL)
{
return sum;
}
return preorderSumNum(root, sum);
}
int preorderSumNum(TreeNode* root, int sum)
{
if (root==NULL)
{
return 0;
}
sum = sum * 10 + root->val;
if (root->left==NULL && root->right==NULL)
{
return sum;
}
return preorderSumNum(root->left, sum) + preorderSumNum(root->right. sum);
}
};