129. Sum Root to Leaf Numbers**
2016-12-24 15:13
281 查看
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) {
return sumNumbers(root,0);
}
private int sumNumbers(TreeNode root, int sum){
if (root==null) return 0;
if(root.left==null&&root.right==null) return sum*10+root.val;
return sumNumbers(root.left,sum*10+root.val) + sumNumbers(root.right,sum*10+root.val);
}
}
总结:基本思路想到了,还需要整理更清晰。落实到代码上。
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) {
return sumNumbers(root,0);
}
private int sumNumbers(TreeNode root, int sum){
if (root==null) return 0;
if(root.left==null&&root.right==null) return sum*10+root.val;
return sumNumbers(root.left,sum*10+root.val) + sumNumbers(root.right,sum*10+root.val);
}
}
总结:基本思路想到了,还需要整理更清晰。落实到代码上。
相关文章推荐
- Javascript基础
- Python中文编码问题
- PHP 反射技术
- 数据流中的中位数
- webstorm 格式化代码及常用快捷键
- Python中的with语句解析和实践
- 消息摘要及其算法扫盲贴
- 9.PHP.ini配置文件中文(2)
- 容易被误解的overflow:hidden
- docker
- 数据结构与算法——线性表 1
- lintcode,搜索二维矩阵
- 大话数据结构-线性表-静态链表
- apach nginx tomcat 负载均衡
- Android 布局优化的几个技巧
- golang读取mysql中null字段出错问题
- 【NOIP2017提高组模拟12.24】C
- 强制关闭Windows下进程
- Xcode8 pod install 报错 “Generating Pods project Abort trap
- 封装一个自己的mvc框架