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 represents the number 1->2
12
.
The Root-to-leaf path represents the number 1->3
13
.
Return the sum = + = 25
.
Method of solving problems: Using DFS pre-order traversal
1 Public classSolution {2 Public intsumnumbers (TreeNode root) {3 if(Root = =NULL) {4 return0;5 }6 returnDFS (root, 0);7 }8 9 //The DFS function is a base-based and from the current node to the leaf node. Ten Private intDFS (TreeNode root,intbase) { One if(Root = =NULL) { A return0; - } - intsum = base * 10 +Root.val; the if(Root.left = =NULL&& Root.right = =NULL) { - returnsum; - } - returnDFS (Root.left, sum) +dfs (root.right, sum); + } -}
Sum Root to Leaf Numbers