129. Sum Root to Leaf Numbers
2016-06-12 22:16
405 查看
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 =
求根到子树的路径的所有和。
常用回溯法。
每当dfs访问到子树时,把和加上即可。
int sum=0;
public int sumNumbers(TreeNode root)
{
if(root==null)
return 0;
inorder(root, String.valueOf(root.val));
return sum;
}
private void inorder(TreeNode t,String s)
{
if(t.left!=null)
inorder(t.left, s+t.left.val);
if(t.left==null&&t.right==null)
sum+=Integer.parseInt(s);
if(t.right!=null)
inorder(t.right, s+t.right.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.
求根到子树的路径的所有和。
常用回溯法。
每当dfs访问到子树时,把和加上即可。
int sum=0;
public int sumNumbers(TreeNode root)
{
if(root==null)
return 0;
inorder(root, String.valueOf(root.val));
return sum;
}
private void inorder(TreeNode t,String s)
{
if(t.left!=null)
inorder(t.left, s+t.left.val);
if(t.left==null&&t.right==null)
sum+=Integer.parseInt(s);
if(t.right!=null)
inorder(t.right, s+t.right.val);
}
相关文章推荐
- 在APP当中调用Android系统摄像头进行视频录制
- 使用HashMap时碰到的串值问题
- 简述C++虚函数作用及底层实现原理
- main方法的参数
- 当EntityFramework爱上AutoMapper
- mongoDB--数据库操作
- 第16章 行为型模式—命令模式
- Apache多站点实现原理和配置
- 嵌入式实时操作系统任务调度算法
- Java中String类的特点
- python逻辑表达
- imx6交叉编译器arm-none-linux-gnueabi-gcc的安装
- 云计算的发展路径和落地形态分别有几种?
- 数据库变量与语句
- 7、js使用正则表达式验证
- 输入一个链表的头结点,从尾到头反过来打印出每个节点的值
- 相机模型(Camera Model)
- java集合入门
- APP开发实战55-实体类、辅助类和三方功能模块设计
- Linux 内核学习内容