【LeetCode】 129. Sum Root to Leaf Numbers
2017-01-21 07:32
363 查看
Given a binary tree containing digits from
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 =
4000
12 + 13 =
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int sumNumbers(TreeNode root) {
return helper(root, 0);
}
private int helper(TreeNode node, int num) {
if (node == null) {
return 0;
}
int temp = num * 10 + node.val;
if (node.left == null && node.right == null) {
return temp;
}
return helper(node.left, temp) + helper(node.right, temp);
}
}
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 =
4000
12 + 13 =
25.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int sumNumbers(TreeNode root) {
return helper(root, 0);
}
private int helper(TreeNode node, int num) {
if (node == null) {
return 0;
}
int temp = num * 10 + node.val;
if (node.left == null && node.right == null) {
return temp;
}
return helper(node.left, temp) + helper(node.right, temp);
}
}
相关文章推荐
- POJ 3624- Charm Bracelet(01背包 滚动数组)
- 图解Linux命令之--wc命令
- OSChina 周六乱弹 ——今年又让支付宝赢了
- C++ crash 堆栈信息获取(三篇)
- 几款国产开源的Windows界面库
- qt之fiddler抓包
- CentOS7需要作的处理
- 在ubuntu下安装free pascal
- 给 Qt sqlite 增加加密功能
- 【数据库开发】Redis消息通知
- Qt 5.6.2 静态编译(VS2013 x86 target xp openssl icu webkit)
- 【数据库开发】C++测试redis中的publish/subscribe
- 【VS开发】【数据库开发】libevent简单入门和介绍
- 【VS开发】【数据库开发】libevent入门
- Sodoku classical backtracking
- 为自己投资,抢先一步,快人百步
- 图解Linux命令之--dmesg命令
- Cool stuff
- ORA-01031 故障处理方法
- JS 日期格式转换