From : 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.
For example,
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
.
/**
* 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;
int sum=0;
add(root, 0, sum);
return sum;
}
void add(TreeNode* node, int cur, int& sum) {
if(!node->left && !node->right) {
sum += cur*10+node->val;
return;
}
cur = cur*10 + node->val;
if(node->left) add(node->left, cur, sum);
if(node->right) add(node->right, cur, sum);
}
};
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int sum = 0;
public int sumNumbers(TreeNode root) {
dfs(root, 0);
return sum;
}
void dfs(TreeNode root, int a) {// 当前root待计算,已累计到a
if(root == null) {
return;
}
a = a*10+root.val;
if(root.left == null && root.right == null) {
sum += a;
return;
}
dfs(root.left, a);
dfs(root.right, a);
}
}