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
.
给定一个二叉树仅包含数字0-9,每一个从根到叶子的路径代表一个数字。
例如从根到叶的路径为1->2->3,那么这个数为123.
得出所有根叶树的和。
写一个函数遍历每条路径,得出每条路径代表的数字,然后加入全局变量sum中,代码如下:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
int sum=0;
public:
int sumNumbers(TreeNode *root) {
if(root==NULL) return 0;
getsum(root,0);
return sum;
}
public:
void getsum(TreeNode *root,int cursum)
{
cursum=cursum*10+root->val;
if(root->left==NULL && root->right==NULL) sum+=cursum;
if(root->left) getsum(root->left,cursum);
if(root->right) getsum(root->right,cursum);
}
};