129. Sum Root to Leaf Numbers
2016-03-21 11:09
78 查看
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 =
Subscribe to see which companies asked this question
dfs
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.
Subscribe to see which companies asked this question
dfs
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { // private static int ret = 0; private int dfs(TreeNode root,int ret){ if(root.left==null&&root.right==null)ret=ret+root.val; if(root.left!=null){ root.left.val=10*root.val+root.left.val; ret = dfs(root.left,ret); } if(root.right!=null){ root.right.val=10*root.val+root.right.val; ret = dfs(root.right,ret); } return ret; } public int sumNumbers(TreeNode root) { int ret = 0; if(root==null)return ret; return dfs(root,ret); } }
相关文章推荐
- 深拷贝与浅拷贝及页面跳转时赋值
- WebAPP(H5)与原生APP的交互设计区别
- 说说List和ArrayList的区别
- laravel遇到"openssl extension is required..."
- C++中的标准IO库详解
- 使用Ajax技术从本地取回xml文件信息
- 【git】git 基础简单梳理
- display:inline-block之用法
- PHP next()移动数组内部指针到下一个元素的位置,并返回该元素 prev()
- php数组指针如何移动到指定单元?
- PHP数组 怎么从指定位置开始查询?比如我想从c开始循环,怎么写?
- <a>标签中href=\"javascript:;\"表示什么意思??
- dedecms网站GBK与UTF-8相互之间怎么转换
- css样式属性加前加*什么意思
- 玉带久了会变色吗
- 织梦DEDECMSV5.7联动类型无法显示的处理方法
- DedeCMS系统自定义字段图片类型调用的路径问题解决办法.doc
- 由于应用程序配置不正确 应用程序未能启动\"的解决办法
- 手机充电慢,或者充电玩游戏玩掉电,解决办法。
- phpmyadmin不需要密码登录的设置方法