LeetCode_129 Sum Root to Leaf Numbers
2015-07-29 16:09
393 查看
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.
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.
int sum = 0; public int sumNumbers(TreeNode root) { if(root == null) return sum; dfs(root, root.val); return sum; } private void dfs(TreeNode root, int num){ if(root == null) return; if(root.left == null&& root.right==null)sum +=num; if (root.left !=null) { dfs(root.left, num*10+root.left.val); } if (root.right != null) { dfs(root.right, num*10+root.right.val); } }
相关文章推荐
- Unity 物理碰撞检测
- Uva524 Primer Ring Problem
- Atom编辑器在Ubuntu下安装(32位推荐,64位有官方deb包)
- 如何理解CMMI-DEV模型中的VER与VAL、及PPQA
- php引用php文件
- memcache/redis/ehcache 缓存整理
- [Docker 官方文档] 理解 Docker
- uboot环境变量设置好后烧写启动内核,文件系统出现的问题
- Ubuntu下搭建tftp服务器最简单方法
- VS2003"无法启动调试 没有正确安装调试器"的解决方法
- 大并发下,数据库的操作
- Unsupported major.minor version 51.0
- 数据库分页查询
- sql——存储过程&触发器(1/3)
- python内置函数部分(一)
- 用python统计文件夹下文本中的单词个数
- 【linux高级程序设计】(第十一章)System V进程间通信 2
- JS日期格式化
- 不吐不快之EJB中有无状态的Session Bean比较
- pandas group by