129. Sum Root to Leaf Numbers
来源:互联网 发布:淘宝模特拍摄视频震惊 编辑:程序博客网 时间:2024/06/05 19:58
Given a binary tree containing digits from 0-9
only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3
which represents the number123
.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path 1->2
represents the number 12
.
The root-to-leaf path 1->3
represents the number 13
.
Return the sum = 12 + 13 = 25
.
Subscribe to see which companies asked this question.
Solution:
Tips:
tree, recursion
Java Code:
/** * 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 (null == root) { return 0; } int[] sum = {0}; sumNumbers(root, "", sum); return sum[0]; } private void sumNumbers(TreeNode root, String s, int[] sum) { if (root == null) { return; } if (root.left == null && root.right == null) { sum[0] += Integer.valueOf(s + root.val); } if (root.left != null) { sumNumbers(root.left, s + root.val, sum); } if (root.right != null) { sumNumbers(root.right, s + root.val, sum); } }}
0 0
- [LeetCode]129.Sum Root to Leaf Numbers
- LeetCode 129. Sum Root to Leaf Numbers
- [leetcode] 129.Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- 【leetcode】129. Sum Root to Leaf Numbers
- [leetcode] 129. Sum Root to Leaf Numbers
- [LeetCode]129. Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers LeetCode
- [LeetCode]129. Sum Root to Leaf Numbers
- leetcode 129. Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- Leetcode 129. Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- LeetCode *** 129. Sum Root to Leaf Numbers
- LeetCode-129.Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- javascript面向对象
- Mybatis-Spring整合
- 洛谷 P3384 【模板】树链剖分
- Spring AOP不拦截从对象内部调用的方法原因
- 个人模板 计算年月日
- 129. Sum Root to Leaf Numbers
- Python安装lxml出错:ERROR: 'xslt-config' 不是内部或外部命令,也不是可运行的程序的解决办法。
- java多线程功力
- mysql 5.7.14+ 版本更改密码, 原来user表的password编程了authentication_string
- css练习:商品分类
- 四道面试题
- IAR 8051 8.30.2 编译 BLE- CC254X_1.4.0例程出错
- Junit 测试 Service 层
- Java IO 装饰者模式