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