Given a Binary Tree Containing digits from0-9
Only, each root-to-leaf path cocould represent a number.
An example is the root-to-leaf path1->2->3
Which represents the number123
.
Find the total sum of all root-to-leaf numbers.
For example,
1 / 2 3
The root-to-leaf path1->2
Represents the number12
.
The root-to-leaf path1->3
Represents the number13
.
Return the sum = 12 + 13 =25
.
Question:
The idea at the beginning is to calculate the list of integers that can be obtained from each node to the leaf node, and then return it to the parent node of the node, then, the list is used to calculate the integer that can be generated from the parent node to the leaf node, however, the problem with this method is that the value of X cannot be determined when calculating the integer generated from the parent node * 10 ^ x + child node to the page node, because the distance from the parent node to the leaf node is unknown. Therefore, this method is not feasible.
Later, I thought about a simpler method: store the final generated integer on the leaf node instead of the root node. Each recursion calculates a sum on the current node, which indicates the integer generated from the root node to the current node, and then passes the sum to the child of the current node, recursively calculate the integer generated from the root node to the child node .....
For example, a tree is shown in:
Finally, sum (123 + 125 + 146) on each node will get the final answer.
The Code is as follows:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */10 public class Solution {11 private int totalSum = 0;12 private void rootList(TreeNode root,int sum){13 if(root == null)14 return;15 sum = sum*10+root.val;16 17 if(root.left == null && root.right == null)18 {19 totalSum += sum;20 return;21 }22 23 rootList(root.left, sum);24 rootList(root.right, sum);25 26 }27 public int sumNumbers(TreeNode root) {28 rootList(root, 0);29 return totalSum;30 }31 }