码迷,mamicode.com
首页 > 其他好文 > 详细

Problem Sum Root to Leaf Numbers

时间:2014-07-07 16:01:34      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   strong   for   

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     }

 

Problem Sum Root to Leaf Numbers,布布扣,bubuko.com

Problem Sum Root to Leaf Numbers

标签:des   style   blog   color   strong   for   

原文地址:http://www.cnblogs.com/liew/p/3815099.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!