Leetcode no. 129
2016-05-27 12:42
288 查看
129. Sum Root to Leaf Numbers
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 = 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) {
if (root==null) return 0;
return toLeaf(root, 0);
}
private int toLeaf(TreeNode root, int sum){
if (root.left==null && root.right==null) return sum*10+root.val;
int left=0, right=0;
if (root.left!=null) left=toLeaf(root.left, sum*10+root.val);
if (root.right!=null) right=toLeaf(root.right, sum*10+root.val);
return left+right;
}
}
Given a binary tree containing digits from
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.
/**
* 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) {
if (root==null) return 0;
return toLeaf(root, 0);
}
private int toLeaf(TreeNode root, int sum){
if (root.left==null && root.right==null) return sum*10+root.val;
int left=0, right=0;
if (root.left!=null) left=toLeaf(root.left, sum*10+root.val);
if (root.right!=null) right=toLeaf(root.right, sum*10+root.val);
return left+right;
}
}
相关文章推荐
- HANA MODEL 创建schema、表,向表导入数据
- mac 下载安装tomcat 并给权限
- MySQL server has gone away 问题的解决方法
- python 正则表达式
- CentOS安装Confluence Wiki步骤
- 用Java写的简单五子棋游戏(原创五子连珠算法)
- Problems for Round
- 计算机视觉&图像处理领域重要期刊汇总
- redis之(十一)redis实现缓存的功能
- 建立一个能运行的spring-mvc程序,至少需要哪些配置以及jar包
- 欢迎使用CSDN-markdown编辑器
- [Java 8] (9) Lambda表达式对递归的优化(下) - 使用备忘录模式(Memoization Pattern) .
- poj 1125
- jar打包通过exe4j转换成exe文件
- Alamofire分析
- Dialog对话框
- [Java 8] (8) Lambda表达式对递归的优化(上) - 使用尾递归 .
- Eclipse常见问题及解决
- C primer plus 第八章 例题练习(递归)
- mysql GET DIAGNOSTICS 语法