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.
思路:本題可以按照先序遍歷來(lái)求和洪灯,對(duì)于每個(gè)結(jié)點(diǎn)虽缕,采用 temp = value* 10 + node->val來(lái)更新值齐唆。注意先序遍歷的寫(xiě)法骄恶,不要多考慮情況赦肃,一開(kāi)始我加的判斷太多了粥喜,其實(shí)根本不需要者祖,只需要判斷傳入的Node是否為空即可;衅!而不需要預(yù)先做判斷梯啤。
代碼如下:
/**
* 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 == nullptr) return 0;
return sum(root,0);
}
int sum(TreeNode *root ,int value) {
if(root == nullptr)
return 0;
int temp = value * 10 + root->val;
if(root->left == nullptr && root->right == nullptr) return temp;
return sum(root->right,temp) + sum(root->left,temp);
}
};