[leetcode]129. Sum Root to Leaf Numbers
[leetcode]129. Sum Root to Leaf Numbers
Analysis
还没工作就想退休—— [每天刷题并不难0.0]
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.
Note: A leaf is a node with no children.
Explanation:
看到树,递归就完事了!
Implement
/**
* 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 sumNumbers(TreeNode* root) {
if(!root)
return 0;
helper(root, 0);
return sum;
}
void helper(TreeNode* node, int tmp){
if(!node->left && !node->right){
tmp = tmp*10+node->val;
sum += tmp;
}
else{
tmp = tmp*10+node->val;
if(node->left)
helper(node->left, tmp);
if(node->right)
helper(node->right, tmp);
}
}
private:
int sum = 0;
};