129. Root node numbers to the leaves and
Questions asked
Given a binary tree, each node that are stored in a digital 0-9, from the root to each leaf node represents a number of paths.
For example, the path from the root to the leaf node 1-> 2-> 3 represents the number 123.
Calculated from the root to the leaf nodes generated by the sum of all the numbers.
Description: leaf node is a node has no child nodes.
示例 1:
输入: [1,2,3]
1
/ \
2 3
输出: 25
解释:
从根到叶子节点路径 1->2 代表数字 12.
从根到叶子节点路径 1->3 代表数字 13.
因此,数字总和 = 12 + 13 = 25.
示例 2:
输入: [4,9,0,5,1]
4
/ \
9 0
/ \
5 1
输出: 1026
解释:
从根到叶子节点路径 4->9->5 代表数字 495.
从根到叶子节点路径 4->9->1 代表数字 491.
从根到叶子节点路径 4->0 代表数字 40.
因此,数字总和 = 495 + 491 + 40 = 1026.
answer
https://github.com/soulmachine/leetcode
class Solution {
public:
int sumNumbers(TreeNode* root) {
return dfs(root,0);
}
private:
int dfs(TreeNode *root,int sum){
if(!root) return 0;
if(root->left == nullptr && root->right == nullptr)
return sum*10+root->val;
return dfs(root->left,sum*10+root->val)+dfs(root->right,sum*10+root->val);
}
};