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

问题

  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 }

 

posted on 2017-08-18 13:38  一个不会coding的girl  阅读(454)  评论(0编辑  收藏  举报

导航