【LeetCode】129. Sum Root to Leaf Numbers 解题报告(Python)
2024-09-06 18:00:54
【LeetCode】129. Sum Root to Leaf Numbers 解题报告(Python)
标签(空格分隔): LeetCode
题目地址:https://leetcode.com/problems/sum-root-to-leaf-numbers/description/
题目描述:
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.
解题方法
这个题和Binary Tree Paths一模一样,前个题是求路径,这个题是把路径按照10的倍数拼接在一起,最后求和即可。
有个技巧就是res = 0
当做参数传给函数,那么函数最后的结果不会影响到res,但是如果把res = [0]
即可。
代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
res = [0]
self.dfs(root, res, root.val)
return res[0]
def dfs(self, root, res, path):
if root.left == None and root.right == None:
res[0] += path
if root.left != None:
self.dfs(root.left, res, path * 10 + root.left.val)
if root.right != None:
self.dfs(root.right, res, path * 10 + root.right.val)
日期
2018 年 2 月 25 日
最新文章
- spider 配置文件参考
- VS2010环境下C++工程相关问题汇总
- bzoj2044: 三维导弹拦截
- 从官方下载 Bootstrap 版本 并写 第一个页面
- hdu 5025 Saving Tang Monk(bfs+状态压缩)
- “DBUtility.DbHelperSQL”的类型初始值设定项引发异常 “DBUtility.DbHelperSQL”的类型初始值设定项引发异常
- cocos2dx 2.14使用UUID
- js操作数据库实现注册和登陆
- 最全的TV视频应用合集,包含50多款客户端,有丰富直播点播
- [转] iOS性能优化技巧
- C#拖曳控件加载,bll报错问题
- Android之一个简单计算器源代码
- slf4j 与 log4j2 实战讲解与日志分割
- javascript之继承
- 【转】每天一个linux命令(23):Linux 目录结构
- 如何为 Go 设计一个通用的日志包
- Java复习第四天
- HyperLedger Fabric 1.4 生产环境使用ca生成msp和tls(12)
- IT界天才少年:比肩雷军、叫板任正非,自己作死了
- base_lr, blobs_lr