1、题目描述:
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.
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.
2、代码实现:
1)、使用递归的方式:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode *root) {
return cal_sum(root, 0);
}
int cal_sum(TreeNode *root, int sum)
{
//只有左右子树都为空时,才产生一个数字;像左子树为空,但右子树不为空的情况,则数字朝右边继续生长,
//左子树不单独形成一个数字,所以root为NULL是返回0而不是sum,只有左右子树都为空时(叶子节点)一个数字才生成并返回
if (!root)
return 0;
if (!root->left && !root->right)
return sum * 10 + root->val;
return cal_sum(root->left, sum * 10 + root->val) + cal_sum(root->right, sum * 10 + root->val);
}
};
2)、也可以使用引用的方式:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode *root) {
if(root==NULL)
return 0;
int cur=0,sum=0;
CalSum(root,cur,sum);
return sum;
}
void CalSum(TreeNode* root,int cur,int& sum){
cur=cur*10+root->val;
if(root->left==NULL && root->right==NULL){
sum+=cur;
return;
}
if(root->left!=NULL)
CalSum(root->left,cur,sum);
if(root->right!=NULL)
CalSum(root->right,cur,sum);
}
};