Sum Root to Leaf Numbers leetcode java
2024-08-31 14:23:34
题目:
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.
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
.
题解:
分析这道题,由根节点往叶节点方向走,就是从高位往地位加和的方向。也就是说,当遍历的节点往叶节点方向走一层的时候,该节点的值应为父节点的值*10+当前节点的值。
由此可以写出代码:
1 int sumhelper(TreeNode root, int levelBase) {
2 if(root == null)
3 return 0;
4
5 if(root.left == null && root.right == null) {
6 return levelBase + root.val;
7 }
8
9 int nextLevelBase = (levelBase + root.val)*10 ;
int leftSubTreeSum = sumhelper(root.left, nextLevelBase);
int rightSubTreeSum = sumhelper(root.right, nextLevelBase);
return leftSubTreeSum + rightSubTreeSum;
}
public int sumNumbers(TreeNode root) {
return sumhelper(root,0);
}
最新文章
- 在Ubuntu 14.04安装和使用Docker
- jQuery中的事件处理
- mouseover和mouseout、mouseenter和mouseleave
- 黄聪:wkhtmtopdf--高分辨率HTML转PDF
- sql语句not in判断条件注意事项
- 折腾iPhone的生活——iPhone 5s 开启 assistive touch 后卡顿的问题
- hdoj 1686 Oulipo【求一个字符串在另一个字符串中出现次数】
- 深入浅出—JAVA(10)
- java-创建线程的两种方式
- 【web开发学习笔记】Structs2 Action学习笔记(一个)
- Python新式类继承的C3算法
- 配置mysql使其允许外部ip进行登录
- Android回调详解
- [BJOI2019]光线[递推]
- [Swift]LeetCode83. 删除排序链表中的重复元素 | Remove Duplicates from Sorted List
- 全志A33移植LCD驱动(ILI9806E)
- node 项目中 koa2 环境搭建 以及项目发布
- 阅读别人的程序(Java篇)
- DVWA的Xss跨站总结
- 【转】WCF光芒下的Web Service
热门文章
- INSTALL_FAILED_CONFLICTING_PROVIDER
- python基础-UDP、进程、进程池、paramike模块
- Codeforces Round #404 (Div. 2) A - Anton and Polyhedrons 水题
- VSCode换行符
- How to properly set clock speed for STM32F4xx devices
- Golang 特性简介
- 使用position:relative制作下边框下的小三角
- Complete uninstall on Mac, HELP!
- 使用jQuery实现图片懒加载原理
- Android 实现页面跳转并传递参数教程