Problem Sum Root to Leaf Numbers

Problem Description:

Given a binary tree containing digits from 0-9 only, 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     public int sumNumbers(TreeNode root) {
 2        int[] sum = {0};
 3         getSum(root, 0, sum);
 4         return sum[0]; 
 5     }
 6     
 7     public void getSum(TreeNode root, int current, int[] sum) {
 8         if (root == null) {
 9             return;
10         }
11 
12         current = current * 10 + root.val;
13 
14         if (root.left == null && root.right == null) {
15             sum[0] +=  current;
16             return;
17         }
18 
19         getSum(root.left, current, sum);
20         getSum(root.right, current, sum);
21 
22 
23     }

 

posted @ 2014-06-29 14:49  HaruHaru  阅读(137)  评论(0编辑  收藏  举报