LeetCode.1022-根到叶路径二进制数之和(Sum of Root To Leaf Binary Numbers)

LeetCode --- 1022. Sum of Root To Leaf Binary Numbers 解题思路 You are given therootof a binary tree where each node has a value0or1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is0 -> 1 -> 1 -> 0 -> 1, then this could represent... 阅读详情

这是小川的第381次更新,第410篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第243题(顺位题号是1022)。给定二叉树,每个节点值为0或1.每个根到叶路径表示以最高有效位开始的二进制数。例如,如果路径为0 -> 1 -> 1 -> 0 -> 1,那么这可能表示二进制的01101,即13。

对于树中的所有叶子节点,请考虑从根到该叶子节点的路径所代表的数字。返回这些数字的总和。

例如:

      1
    /   \
   0     1
  / \   / \
 0   1 0   1

输入:[1,0,1,0,1,0,1]
输出:22
说明:(100)+(101)+(110)+(111)= 4 + 5 + 6 + 7 = 22

注意:

  • 树中的节点数介于1和1000之间。

  • node.val是0或1。

  • 答案不会超过2^31 - 1。

02 第一种解法

递归的方式解题。

结合题目给的示例来看,可以将该二叉树分为两部分,left和right,left那一支有两条路径100和101,直接做加法就是4+5=9;right那一支也有两条路径110和111,直接做加法就是6+7=13,我们可以将求和拆分成左子树、右子树之和来做。

如果当前节点为空,返回0。如果当前节点如果为叶子节点(没有左子节点和右子节点的节点),就返回此路径所表示的整数。计算路径上的二进制数,可以通用此代码:int val = val*2 + currentNodeValue;,和前天的那道题目在处理累加二进制字符串上类似。

public int sumRootToLeaf(TreeNode root) {
    return getSum(root, 0);
}

public int getSum(TreeNode root, int sum) {
    if (root == null) {
        return 0;
    }
    // 换成 sum = (sum<<1) + root.val; 效果一样
    sum = sum*2 + root.val;
    // 当前节点为叶子节点时
    if (root.left == null && root.right == null) {
        return sum;
    }
    return getSum(root.left, sum) + getSum(root.right, sum);
}

03 第二种解法

迭代的方式解题。借助两个栈来实现,思路和上面类似。

public int sumRootToLeaf2(TreeNode root) {
    if (root == null) {
        return 0;
    }
    int sum = 0;
    // 存节点
    Stack<TreeNode> stack = new Stack<TreeNode>();
    // 存路径所代表整数
    Stack<Integer> prevSum = new Stack<Integer>();
    stack.push(root);
    prevSum.push(root.val);
    while (!stack.isEmpty()) {
        TreeNode temp = stack.pop();
        Integer tempSum = prevSum.pop();
        // 左子树
        if (temp.left != null) {
            stack.push(temp.left);
            prevSum.push(tempSum*2 + temp.left.val);
        }
        // 右子树
        if (temp.right != null) {
            stack.push(temp.right);
            prevSum.push(tempSum*2 + temp.right.val);
        }
        // 叶子节点,累加完整路径所表示的整数
        if (temp.left == null && temp.right == null) {
            sum += tempSum;
        }
    }
    return sum;
}

04 小结

算法专题目前已连续日更超过七个月,算法题文章249+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

基于STM32的双串口同时工作的详细指南(含完整代码示例) STM32是STMicroelectronics(意法半导体)公司推出的一系列基于ARM Cortex-M内核的微控制器,广泛应用于嵌入式系统中。STM32系列微控制器具有高性能、低功耗和丰富的外设接口,适用于各种应用场景。USART(Universal Synchronous/Asynchronous Receiver/Transmitter)和UART(Universal Asynchronous Receiver/Transmitter)是串口通信的两种方式。 阅读详情

相关推荐

手把手教你用LangChain4j打造一个“会追问”的AI客服:以航空货运下单为例

本文详细介绍了如何使用LangChain4j构建一个能够主动追问的航空货运AI客服系统。通过对话状态管理、信息缺口识别和渐进式引导等核心技术,实现高效的多轮对话交互。文章包含从交互设计到代码实现的完整指南,特别强调了提示词(Prompt)在优化AI行为中的关键作用,帮助开发者打造更智能的客服解决方案。

weixin_28731223的博客 159

1022. Sum of Root To Leaf Binary Numbers

题目链接:https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/ 解题思路:本题参考博客,原博客对和值除1000000007,这个是为了防止数值溢出,另外递归题要理清设计的形参代表的物理意义,这样就好解题了. 代码: /** * Definition for a binary tree node. * struct T...

virgilshi的博客 300

2023-07-04 Fast-Lio论文中公式(6)与BCH公式中近似雅可比公式的一致性推导

将(1)式代入(6)式,就有。

wmorries的博客 486

【LeetCode】1022. Sum of Root To Leaf Binary Numbers 解题报告(Python)

作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录题目描述题目大意解题方法DFS日期 题目地址:https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/ 题目描述 Given a binary tree, each node has value 0 or 1...

负雪明烛 1719

PCL 八叉树的使用

八叉树(Octree)是一种空间划分的数据结构,广泛应用于三维点云的处理和分析。八叉树通过将空间递归地划分为八个子区域,可以有效地组织和索引三维点数据,提升点云的查询、降采样和配准等操作的效率。

纵马踏花向自由 1665

Luma AI技术浅析(一)

是一款基于人工智能的3D内容生成平台,旨在通过深度学习技术实现高效、高质量的3D场景、物体和动画的生成。Luma AI 主要利用了等技术,以实现从图像、视频到3D模型的转换和生成。

m0_75253143的博客 1740

leetcode No1022. Sum of Root To Leaf Binary Numbers

Welcom to follow Dufre/LeetCode Question Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if th...

Dufre 578

RK3588 部署 ArcFace(r100)人脸识别模型:ONNX 转 RKNN 全流程详解

本文介绍了将ArcFace人脸识别模型转换为RKNN格式并部署到RK3588 NPU的方法。ArcFace是主流的人脸特征提取模型,适用于1:1比对和1:N检索等场景。文章详细说明了模型特点(输入112x112 RGB图像,输出512维特征向量)及转换步骤:首先使用torch2onnx将PyTorch模型转为ONNX格式,再通过RKNN工具进行量化转换。提供了完整的Python转换代码,包括预处理配置、模型加载、构建和导出过程。该方法能有效提升边缘设备上的人脸识别实时性,适用于门禁、考勤等应用场景。

J。 441

LeetCode-Sum Root to Leaf Numbers一种算法

LeetCode-Sum Root to Leaf Numbers一种算法 题目链接:https://leetcode.com/problems/sum-root-to-leaf-numbers/description/ Given a binary tree containing digits from 0-9 only, each root-to-leaf path could repre...

qq_30985149的博客 277

Cesium初级开发教程之三十:Primitive集合

教程示例网站:https://thomaz529.github.io。

487

【Unity实战篇 】| Unity实现 文本框可以自适应大小,到达最大宽度之后再缩小字体

Unity实现 Text文本框可以自适应大小,到达最大宽度之后再缩小字体 需求:在文本框可以自适应大小拉伸的前提下,增加一个最大限制宽度,使其到达最大宽度后 再启用 Best Fit 实现自适应改变文字大小以适应文本框的大小。 在Unity中经常会用到文本组件的自适应大小功能,一般使用HorizontalLayoutGroup和ContentSizeFitter组件配合即可实现文本自适应的效果。

努力前行,总会成为自己心中的那道光 3万+

LeetCode1022.Sum of Root To Leaf Binary Numbers(从根到叶的二进制数之和)

1022.Sum of Root To Leaf Binary Numbers(从根到叶的二进制数之和)DescriptionDifficulty: easyExample 1:Note:分析参考代码 Description Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a b...

redtongue的博客 409

Openclaw 错误分析 与 解决方案 之:Selected model is at capacity. Try a different model, or wait and retry.

Openclaw 错误分析 与 解决方案 :Selected model is at capacity. Try a different model, or wait and retry.

多媒体编程、网络编程、系统编程、网络安全编程、驱动编程 6508

LeetCode 1022. 从根到叶的二进制数之和

目录结构 1.题目 2.题解 1.题目 给出一棵二叉树,其上每个结点的值都是0或1。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。例如,如果路径为0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数01101,也就是13。 对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。 以10^9 + 7为模,返回这些数字之和。 示例: 输入:[1,0,1,0,1,0,1] 输出:22 解释:(100) + (101)...

HarvestWu的博客 297

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

1022. Sum of Root To Leaf Binary Numbers*

1022. Sum of Root To Leaf Binary Numbers* https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/ 题目描述 Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a b...

珍妮的选择的博客 326

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Leetcode 1022.从根到叶的二进制数之和(Sum of Root To Leaf Binary Numbers)

Leetcode 1022.从根到叶的二进制数之和 1 题目描述(Leetcode题目链接)   给出一棵二叉树,其上每个结点的值都是 0 或 1 。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。例如,如果路径为 0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数 01101,也就是 13 。 对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。 以 10^9 + 7 为模,返回这些数字之和。 输入:[1,0,1,0,1,0,1] 输出:22 解

qq_39378221的博客 165

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

(Java)leetcode-1022 Sum of Root To Leaf Binary Numbers(从根到叶的二进制数之和)

求二叉树中,根至叶子的二进制数之和

不思量 257

LeetCode - 1022 - 从根到叶的二进制数之和(sum-of-root-to-leaf-binary-numbers

一 目录 不折腾的前端,和咸鱼有什么区别目录一 目录二 前言三 解题及测试四 LeetCode Submit五 解题思路二 前言 难度:简单涉及知识:树题目地址:https://leet...

weixin_41806099的博客 181

1022. Sum of Root To Leaf Binary Numbers从根到叶的二进制数之和

网址:https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/ 递归调用求和,同时注意%1000000007的位置 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *l...

weixin_33861800的博客 229

[LeetCode] 1022. Sum of Root To Leaf Binary Numbers

原题链接

Ber03的博客 440

LeetCode //C - 1022. Sum of Root To Leaf Binary Numbers

This problem asks you to calculate the sum of the binary representations of all paths from the root to a leaf in a binary tree. Each node has a value of 0 or 1, and each path from the root to a leaf forms a binary number with the most significant bit first

Made in Code 398

LeetCode 1022. Sum of Root To Leaf Binary Numbers

Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 ->...

katrina95的博客 347

【LeetCode】1022. Sum of Root To Leaf Binary Numbers

Given a binary tree, each node has value 0 or 1.  Each root-to-leaf path represents a binary number starting with the most significant bit.  For example, if the path is 0 -> 1 -> ...

a342500329a的专栏 239

LeetCode #1022. Sum of Root To Leaf Binary Numbers

题目描述: Given a binary tree, each node has value0or1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is0 -> 1 -> 1 -> ...

LawFile的博客 228

[Swift]LeetCode1022. 从根到叶的二进制数之和 | Sum of Root To Leaf Binary Numbers

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)➤GitHub地址:https://github.com/strengthen/LeetCode➤原文地址:https://www.cnblogs.com/stren...

weixin_30342827的博客 119
上一篇: LeetCode.1021-删除最外面的括号(Remove Outermost Parentheses)
下一篇: LeetCode.1025-除数游戏(Divisor Game)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址