Title:
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.
Example 1:
Input: [1,2,3]
1
/
2 3
Output: 25
Explanation:
from the root to a leaf node of the path 1-> 2 represents a number 12
from the root to a leaf node of the path 1-> 3 represents the number 13.
Thus, the digital sum = 12 + 13 = 25.
class Solution {
int res = 0;
public int sumNumbers(TreeNode root) {
sumNumbers(root, 0);
return res;
}
private void sumNumbers(TreeNode node, int num) {
if (node == null)
return;
num = num * 10 + node.val;
if (node.left == null && node.right == null) {
res += num;
}
sumNumbers(node.left, num);
sumNumbers(node.right, num);
}
}