博客转载请注明地址:http://blog.csdn.net/sunliymonkey/article/details/48272171
题目描述
题目地址:https://leetcode.com/problems/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 number 123.
Find the total sum of all root-to-leaf numbers.
样例
输入:
1
/ \
2 3
输出:
25
考察点
- 树的遍历
陷阱
无
Code
/**
* 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 {
public:
int sum;
void dfs(TreeNode *x, int number){
if(!x){
return;
}
number = number * 10 + x->val;
if(!x->left && !x->right){
sum += number;
}else{
dfs(x->left, number);
dfs(x->right, number);
}
}
int sumNumbers(TreeNode* root) {
sum = 0;
dfs(root, 0);
return sum;
}
};