博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Middle-题目46:129. Sum Root to Leaf Numbers
阅读量:2432 次
发布时间:2019-05-10

本文共 1187 字,大约阅读时间需要 3 分钟。

题目原文:

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.
题目大意:
有一个二叉树,节点是0-9构成的数字,这样从根节点到叶子节点的每一条路径构成一个数,计算所有路径上的数的和。
题目分析:
本题就是一个记忆化的前序遍历,一直记录着前面的数,每次向孩子搜索的时候把当前数×10加上当前节点的数,搜到叶子节点的时候加到当前的和里面。
源码:(language:java)

public class Solution {    private int currentTotal = 0;    public int sumNumbers(TreeNode root) {       dfs(root,0);       return currentTotal;    }    private void dfs(TreeNode node, int currentSum) {        if(node == null)            return;        else if(isLeaf(node)) {            currentSum+=node.val;            currentTotal+=currentSum;        }        else {            currentSum+=node.val;            dfs(node.left,currentSum*10);            dfs(node.right,currentSum*10);        }    }    private boolean isLeaf(TreeNode node) {        return node.left==null && node.right==null;    }}

成绩:

1ms,beats 28.93%,众数1ms,60.87%

转载地址:http://mfomb.baihongyu.com/

你可能感兴趣的文章
真相了 | 敲代码时,程序员戴耳机究竟在听什么?
查看>>
麒麟信安面向场景化创新,赋能openEuler商业验证
查看>>
3 年培养 10 万“码农”,郑州推出“码农计划”
查看>>
去年我年薪 30W,今年我一天做 3 顿饭
查看>>
入职大厂,我容易吗?
查看>>
漫画:什么是加密算法?
查看>>
程序员是如何运用增长思维找到女朋友?
查看>>
“离开360时,它只给了我一块钱”
查看>>
漫话:如何给女朋友解释什么是RPC
查看>>
如何从零开始两天撸一个微信小程序?!(内含源码)
查看>>
女神?御姐?文艺?这样的程序媛你绝没见过! | 程序员有话说
查看>>
“软件外包城”下的马鞍山 | 程序员有话说
查看>>
程序员如何实现财富自由?
查看>>
你我的父母,都在被互联网“割韭菜”
查看>>
程序员下班后都忙些啥?| 程序员有话说
查看>>
Java 帝国对 Python 的渗透能成功吗?
查看>>
程序员写代码没激情该怎么破?
查看>>
漫画 | 一个前端渣渣的成功逆袭
查看>>
与吴恩达并肩战斗,她是 AI 界的女超人!|人物志
查看>>
微信手机 WeOS 的可行性到底有多大?
查看>>