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 = + = 25 .
Problem Solving Ideas:
Recursively, the Java implementation is as follows:
static public int sumnumbers (TreeNode root) { if (root==null) return 0; Return Sumnumbers (root,0); } public static int Sumnumbers (TreeNode root,int res) { if (root.left==null&&root.right==null) return Res*10+root.val; if (root.left==null) return sumnumbers (root.right,res*10+root.val); if (root.right==null) return sumnumbers (root.left,res*10+root.val); Return Sumnumbers (Root.left,res*10+root.val) +sumnumbers (root.right,res*10+root.val); }
Java for Leetcode 129 Sum Root to Leaf Numbers