Sum Root to Leaf Numbers
2015-08-08 21:14
387 查看
Given a binary tree containing digits from
could represent a number.
An example is the root-to-leaf path
Find the total sum of all root-to-leaf numbers.
For example,
The root-to-leaf path
The root-to-leaf path
Return the sum = 12 + 13 =
0-9only, each root-to-leaf path
could represent a number.
An example is the root-to-leaf path
1->2->3which 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->2represents the number
12.
The root-to-leaf path
1->3represents the number
13.
Return the sum = 12 + 13 =
25.
public class Solution { public int sumNumbers(TreeNode root) { return dfs(root,0); } public int dfs(TreeNode root,int pre){ if(root == null){ return 0; } int sum = root.val + pre*10; if(root.left == null && root.right == null){ return sum; } return dfs(root.left,sum)+dfs(root.right,sum); } }
相关文章推荐
- 两种比较“强壮”的单例代码。
- [M]带属性块参照的转换
- 博客园文章编辑器【客户端应用程序】V2.0.0发布,命名为51cnblogs
- 扫描线 - UVALive - 6864 Strange Antennas
- Linux中命令行和图形界面之间切换
- [转]数据中心网络虚拟化 隧道技术
- 【数论+dp】codeforces559C Gerald and Giant Chess
- 兼容的可视区高度和宽度
- iOS 调试用Log()与随机颜色设置
- 为什么和其他语言相比C语言是快速的语言
- Wayland与Weston简介
- windows内存管理的几种方式的优缺点
- STM32学习笔记 ——流水灯
- 数组
- nginx 开展对RT5350
- css基础与选择器——精通css学习笔记(一)
- 【LeetCode】165 - Compare Version Numbers
- 在线捉鬼游戏开发之二 - 设计业务对象与对象职责划分(3)
- MongoDB学习笔记记录(C#)
- 在 IntelliJ IDEA 14.1.4 上搭建 JFinal 開發環境 (Gradle 版)