LeetCode OJ-129.Sum Root to Leaf Numbers
题目描述
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 number123
.Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path
1->2
represents the number12
.
The root-to-leaf path1->3
represents the number13
.Return the sum = 12 + 13 =
25
.
题目理解
由根节点到最下层的叶节点组成的一条路径表示一个数,如题目中说的,1->2->3,则表示123。题目要求的是二叉树的所有路径代表的数之和,这里可以用简单的先序遍历来处理,每次向字符串中添加该节点表示的数字字符,当遇到最下层的叶节点后,则将字符串转为整型值,做求和。结尾位置要将开头添加的字符删除,做回溯处理。
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void cal_sum(TreeNode *root, string &nums, int &sum)
{
if (root == 0) {
return ;
}
nums.push_back('0' + root->val);
if (root != 0 && root->left == 0 && root->right == 0) {
sum += stoi(nums);
}
cal_sum(root->left, nums, sum);
cal_sum(root->right, nums, sum);
nums.pop_back();
return ;
}
class Solution {
public:
int sumNumbers(TreeNode* root) {
int sum = 0;
string nums;
cal_sum(root, nums, sum);
return sum;
}
};