当前位置: 首页 > news >正文

LeetCode|938. Range Sum of BST

.

序言

开启python刷题时代,主要也是为了面试。

.

题目

Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].

Example 1:

  • Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
  • Output: 32
  • Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.

Example 2:

  • Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
  • Output: 23
  • Explanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.

Constraints:

  • The number of nodes in the tree is in the range [1, 2 * 104].
  • 1 <= Node.val <= 105
  • 1 <= low <= high <= 105
  • All Node.val are unique.

.

思路

简单的树遍历问题,可以用DFS也可以用BFS。
都是第一次用python写,决定先用DFS试试。

DFS遍历树节点,判断每个节点的val是否大于low并且小于high。

.

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:def sumVal(root):return root.val if low <= root.val <= high else 0def searchTree(root):if root is None:return 0return sumVal(root) + searchTree(root.left) + searchTree(root.right)return searchTree(root)

.

后序

python和C++的语法差异比我想象中的大一些。
目前感觉确实要容易很多。
继续加油!

.

相关文章:

  • Python中的列表推导式和字典推导式:优雅且高效的数据结构生成方式
  • 每天坚持写java锻炼能力---第一天(6.4)
  • javaweb的新能源充电系统的设计
  • 【JS】JavaScript编程语言-(Object)对象属性标志与对象属性描述符(2024-06-05)
  • 大模型日报2024-06-06
  • RabbitMQ(五)集群配置、Management UI
  • UFS协议—新手快速入门(二)【5-6】
  • Redis使用中的性能优化——搭建Redis的监测服务
  • 显卡分类及特性详解
  • C语言scanf( ) 函数的格式控制包括哪些?
  • 【TensorFlow深度学习】Adam优化器的工作原理与配置细节
  • ROS学习记录:自定义消息类型
  • 数据库资源评估:构建高效数据架构的基础
  • 动态规划(多重背包问题+二进制优化)
  • 在 SEO 中,一个好的网页必须具备哪些 HTML 标签和属性?
  • 自己简单写的 事件订阅机制
  • 〔开发系列〕一次关于小程序开发的深度总结
  • CSS 提示工具(Tooltip)
  • 复习Javascript专题(四):js中的深浅拷贝
  • 官方新出的 Kotlin 扩展库 KTX,到底帮你干了什么?
  • 精彩代码 vue.js
  • 力扣(LeetCode)21
  • 嵌入式文件系统
  • 译自由幺半群
  • 优化 Vue 项目编译文件大小
  • elasticsearch-head插件安装
  • ionic异常记录
  • 哈罗单车融资几十亿元,蚂蚁金服与春华资本加持 ...
  • ​插件化DPI在商用WIFI中的价值
  • ## 临床数据 两两比较 加显著性boxplot加显著性
  • #NOIP 2014#day.2 T1 无限网络发射器选址
  • (1)bark-ml
  • (1)安装hadoop之虚拟机准备(配置IP与主机名)
  • (2022 CVPR) Unbiased Teacher v2
  • (arch)linux 转换文件编码格式
  • (附源码)springboot金融新闻信息服务系统 毕业设计651450
  • (蓝桥杯每日一题)love
  • (理论篇)httpmoudle和httphandler一览
  • (力扣记录)1448. 统计二叉树中好节点的数目
  • (四)opengl函数加载和错误处理
  • (译)2019年前端性能优化清单 — 下篇
  • (转载)CentOS查看系统信息|CentOS查看命令
  • *p++,*(p++),*++p,(*p)++区别?
  • .apk文件,IIS不支持下载解决
  • .bat批处理(十一):替换字符串中包含百分号%的子串
  • .htaccess配置常用技巧
  • .NET Core使用NPOI导出复杂,美观的Excel详解
  • .net程序集学习心得
  • .NET开源的一个小而快并且功能强大的 Windows 动态桌面软件 - DreamScene2
  • .NET与java的MVC模式(2):struts2核心工作流程与原理
  • ::before和::after 常见的用法
  • @ComponentScan比较
  • @staticmethod和@classmethod的作用与区别
  • [ element-ui:table ] 设置table中某些行数据禁止被选中,通过selectable 定义方法解决
  • [ Linux ] Linux信号概述 信号的产生