【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 日

最新文章

  1. spider 配置文件参考
  2. VS2010环境下C++工程相关问题汇总
  3. bzoj2044: 三维导弹拦截
  4. 从官方下载 Bootstrap 版本 并写 第一个页面
  5. hdu 5025 Saving Tang Monk(bfs+状态压缩)
  6. “DBUtility.DbHelperSQL”的类型初始值设定项引发异常 “DBUtility.DbHelperSQL”的类型初始值设定项引发异常
  7. cocos2dx 2.14使用UUID
  8. js操作数据库实现注册和登陆
  9. 最全的TV视频应用合集,包含50多款客户端,有丰富直播点播
  10. [转] iOS性能优化技巧
  11. C#拖曳控件加载,bll报错问题
  12. Android之一个简单计算器源代码
  13. slf4j 与 log4j2 实战讲解与日志分割
  14. javascript之继承
  15. 【转】每天一个linux命令(23):Linux 目录结构
  16. 如何为 Go 设计一个通用的日志包
  17. Java复习第四天
  18. HyperLedger Fabric 1.4 生产环境使用ca生成msp和tls(12)
  19. IT界天才少年:比肩雷军、叫板任正非,自己作死了
  20. base_lr, blobs_lr

热门文章

  1. perl练习——计算点突变
  2. SIG -MESH -1
  3. 移动测试(web和app)及app测试实战
  4. 在Idea上用JDBC连接mysql数据库
  5. day27 网络编程
  6. HTTP请求 Java API
  7. ES6必知,变量的结构赋值。
  8. vim中搜索指定单词(不加前后缀)
  9. Shell脚本字符串截取方法总结
  10. HttpClient连接池设置引发的一次雪崩