当前位置:网站首页>力扣解法汇总1022-从根到叶的二进制数之和
力扣解法汇总1022-从根到叶的二进制数之和
2022-06-12 02:03:00 【失落夏天】
目录链接:
力扣编程题-解法汇总_分享+记录-CSDN博客
GitHub同步刷题项目:
https://github.com/September26/java-algorithms
原题链接:
力扣
描述:
给出一棵二叉树,其上每个结点的值都是 0 或 1 。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。
例如,如果路径为 0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数 01101,也就是 13 。
对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。
返回这些数字之和。题目数据保证答案是一个 32 位 整数。
示例 1:
输入:root = [1,0,1,0,1,0,1]
输出:22
解释:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
示例 2:
输入:root = [0]
输出:0
提示:
树中的节点数在 [1, 1000] 范围内
Node.val 仅为 0 或 1
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sum-of-root-to-leaf-binary-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
* 解题思路: * 递归遍历所有节点。每次遍历节点时,接受根结点传递过来的累加值,然后加上当前值求出当前节点的值。 * 如果节点是叶子节点,则计算SUM值。 * 如果不是,则传递当前节点的值并递归。
代码:
public class Solution1022 {
int sum = 0;
public int sumRootToLeaf(TreeNode root) {
ergodic(root, 0);
return sum;
}
private void ergodic(TreeNode root, int i) {
int current = (i << 1) + root.val;
if (root.right == null && root.left == null) {
sum += current;
return;
}
if (root.left != null) {
ergodic(root.left, current);
}
if (root.right != null) {
ergodic(root.right, current);
}
}
}边栏推荐
- Google Ads 的优势
- [从零开始学习FPGA编程-19]:快速入门篇 - 操作步骤4-1- Verilog 软件下载与开发环境的搭建- Altera Quartus II版本
- What are the preparations for setting up Google search advertising series?
- Graphical data analysis | business analysis and data mining
- Fatal error in launcher: unable to create process using
- Invert words in a string (split, double ended queue)
- Basic use of MATLAB
- Lua function
- Alicloud OSS file upload system
- Niuke monthly race 14- simple counting
猜你喜欢

RPA introduction

Spiral matrix (skill)

How to automatically color cells in Excel

Google Ads 竞价的运作机制

Ozzanmation action system based on SSE

Data system provider Jidao technology joins dragon lizard community

Explore performance optimization! Performance improvement from 2 months to 4 hours!

Does the virtual host have independent IP

Operating mechanism of Google ads bidding

Master of a famous school has been working hard for 5 years. AI has no paper. How can the tutor free range?
随机推荐
Redis集群更换节点IP后如何恢复集群并保留完整集群数据
聯調這夜,我把同事打了...
Huawei, this is too strong
lua 函数
Explore performance optimization! Performance improvement from 2 months to 4 hours!
Linux (centos7) installer mysql - 5.7
Basic use of MATLAB
Wechat applet - a case of comparing the size of numbers
LeetCode Algorithm 1791. 找出星型图的中心节点
Manually tear the linked list (insert, delete, sort) and pointer operation
Websocket is closed after 10 seconds of background switching
Modification of system module information of PHP security development 12 blog system
Linux(CentOS7)安裝MySQL-5.7版本
matplotlib. pyplot. Bar chart (II)
Niuke monthly race 14- simple counting
商城开发知识点
php安全开放10文章列表模块的分页编写
adb命令 利用jks文件给apk签名
C asynchronous programming from simple to deep (III) details awaiter
2022 blind box applet app has become a new drainage outlet for enterprises