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

Posted 一个不会coding的girl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了树——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 }

 

以上是关于树——sum-root-to-leaf-numbers(根到叶节点数字之和)的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 叶子数量的总和来源:http://oj.leetcode.com/problems/sum-root-to-leaf-numbers/

129 Sum Root to Leaf Numbers

Leetcode[129]-Sum Root to Leaf Numbers

[LeetCode] 129. 求根到叶子节点数字之和

129. 求根节点到叶节点数字之和

129. 求根节点到叶节点数字之和