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 number 123.

Find the total sum of all root-to-leaf numbers.

Note: A leaf is a node with no children.

Example:

Input: [1,2,3]
1
/ \
2 3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int res = 0;
public int sumNumbers(TreeNode root) {
helper(root, 0);
return res;
} private void helper(TreeNode root, int sum) {
if (root == null) {
return;
}
int curSum = 10 * sum + root.val;
if (root.left == null && root.right == null) {
res += curSum;
}
helper(root.left, curSum);
helper(root.right, curSum);
}
}

最新文章

  1. BZOJ1562——[NOI2009]变换序列
  2. NSIS总结1——以管理权限运行
  3. (九)STM32之AFIO
  4. Oracle 触发器,事物
  5. Javascript中字符串转换成Date的方法
  6. leetcode 5 :Longest Palindromic Substring 找出最长回文子串
  7. PHP微信公众号 access_token缓存
  8. JBoss部属和EJB调用-EJB3.0入门经典学习笔记(2)
  9. CentOS下Mysql安装教程
  10. Raft详解-启动后运行期间代码
  11. C#调用WebService接口实现天气预报在web前端显示
  12. Relocation 状态压缩DP
  13. C++异常层次结构
  14. Fedora Linux安装deb包
  15. Nginx的配置与部署研究,Upstream负载均衡模块
  16. PHP Math 函数 mt_rand() 使用 Mersenne Twister 算法返回随机整数。
  17. Android-事件分发机制框架概述
  18. jqgrid 编辑行、新增行、删除行、保存行
  19. 使用Spring Cloud Security OAuth2搭建授权服务
  20. js弹出层的插件

热门文章

  1. 北邮14&18年软院机试【参考】答案
  2. c语言:自增自减运算符的操作详解
  3. Ubuntu的奇技淫巧
  4. ubuntu搭建web服务器
  5. CentOS8上用Docker部署开源项目Tcloud
  6. [代码审计]PCWAP
  7. StringBuiler和StringBuffer的区别
  8. 题解-------[ZJOI2009]对称的正方形
  9. urlopen error [errno 10060]的解决思路
  10. 1051: [HAOI2006]受欢迎的牛 (tarjan强连通分量+缩点)