Sum Root to Leaf Numbers
Given a binary tree containing digits from 0-9 to, 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.
Solution 1:
Use recursion to complete. All we have to do is add the path of the left and right subtree.
When base case:root is a leaf node, the path is calculated directly. We use the pre to retain the value of the calculated number from the previous layer. So the current root node should be
*10 the value of the previous layer to the root value.
1 /**2 * Definition for binary tree3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One Public intsumnumbers (TreeNode root) { A returnDFS (root, 0); - } - the Public intDFS (TreeNode root,intpre) { - if(Root = =NULL) { - return0; - } + - intCur = Pre * 10 +Root.val; + if(Root.left = =NULL&& Root.right = =NULL) { A returncur; at } - - returnDFS (root.left, cur) +dfs (root.right, cur); - } -}View Code
GITHUB:
Https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/SumNumbers_1208_2014.java
Leetcode:sum Root to Leaf Numbers problem solving report