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

树——sum-root-to-leaf-numbers(根到叶节点数字之和)

时间:2017-08-18 14:31:04      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:root   repr   ber   nts   represent   path   class   amp   log   

问题

  Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.

  An example is the root-to-leaf path1->2->3which represents the number123.

  Find the total sum of all root-to-leaf numbers.

  For example,

      1
     /     2   3

  The root-to-leaf path1->2represents the number12.
  The root-to-leaf path1->3represents the number13.

  Return the sum = 12 + 13 =25.

 

代码

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int sumNumbers(TreeNode root) {
12        int sum = 0;
13        if(root==null)
14            return sum;
15        return sumNumbers(root,sum);
16     }
17    
18     public int sumNumbers(TreeNode root, int sum){
19         if(root==null)
20             return 0;
21         sum = sum*10+root.val;
22         if(root.left==null && root.right==null)
23             return sum;
24         return sumNumbers(root.left, sum) + sumNumbers(root.right, sum);
25     }
26 }

 

树——sum-root-to-leaf-numbers(根到叶节点数字之和)

标签:root   repr   ber   nts   represent   path   class   amp   log   

原文地址:http://www.cnblogs.com/jiqianqian/p/7389195.html

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