Question:
Given a binary tree containing digits from only 0-9 , 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
The answer is the exhaustive traversal of the two-fork tree:
C # version:
/** Definition for binary tree * public class TreeNode {* public int val; * Public TreeNode left; * publi c TreeNode right; * Public TreeNode (int x) {val = x;} }*/ Public classSolution {Private intresult=0; Public intsumnumbers (TreeNode root) {if(root==NULL) { return 0; } Solve (Root,0); returnresult; } Public Static voidSolve (TreeNode root,intsum) { if(root.left==NULL&&root.right==NULL) Result+ = (sum*Ten+root.val); if(root.left!=NULL) Solve (root.left,sum*Ten+root.val); if(root.right!=NULL) Solve (root.right,sum*Ten+root.val); } }
This result can be run.
One of the minor problems is that when result is declared as a static variable, the program gives an error.
The reason is not known at the moment.
Wait for the answer.
"Leetcode" Sum Root to Leaf Numbers