129. Sum Root to Leaf Numbers

栏目: 数据库 · 发布时间: 6年前

内容简介: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.

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.

Note: A leaf is a node with no children.

Example:

Input: [1,2,3]
    1
   / \
  2   3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.

Example 2:

Input: [4,9,0,5,1]
    4
   / \
  9   0
 / \
5   1
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.

难度:medium

题目:给定结点值只包含0-9的二叉树,每条从根到叶子的路径表示一个整数。找出所有这样的数并返回其和。

注意:叶结点即没有左右子结点

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int sumNumbers(TreeNode root) {
        return sumNumbers(root, "");
    }
    
    private int sumNumbers(TreeNode root, String s) {
        if (null == root) {
            return 0;
        }
        s += root.val;
        if (null == root.left && null == root.right) {
            return Integer.parseInt(s);
        }
        
        return sumNumbers(root.left, s) + sumNumbers(root.right, s);
    }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

硅谷之火

硅谷之火

迈克尔·斯韦因 / 王建华 / 机械工业出版社 / 2001-1-1 / 34.00

我们今天正处于这样一个时代:充满幻想的人们发现他们获得了他们曾经梦寐以求的力量,并且可以利用这个力量来改造我们的世界。 这是个转折的时代,跨国公司迷失了发展方向,而小企业家却举起了计算机革命的大旗,成了开拓未来的先锋。在这个时代里,计算机奇才的脸上露出了胜利的微笑,胸怀 大志者成了富有理想的人,而富有理想的人则成了亿万富翁。这是一场真正的革命,它促使人们变得伟大,变得富有而充满理想,自豪而富......一起来看看 《硅谷之火》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

SHA 加密
SHA 加密

SHA 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具