题目: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.
例子:
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
.
解题思路:题目意思很简单,就是树的根结点到每个叶子结点的路径上的数字都会组合成一个数值,将这些数值加起来就是需要的答案;这里使用DFS算法进行解题,代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
int dfsSum(TreeNode* current, int a){
if(current == NULL)
return 0;
a = a*10 + current->val;
int leftsum = 0,rightsum = 0;
if(current->left == NULL && current->right == NULL)
return a;
if(!(current->left == NULL))
leftsum = dfsSum(current->left,a);
if(!(current->right == NULL))
rightsum = dfsSum(current->right,a);
return leftsum + rightsum;
}
public:
int sumNumbers(TreeNode* root) {
int sum = 0;
return dfsSum(root,sum);
}
};