当前位置:网站首页>leetcode 938. 二叉搜索树的范围和
leetcode 938. 二叉搜索树的范围和
2022-07-21 14:22:00 【进击的code儿】
938. 二叉搜索树的范围和
一、题目
1.题目描述
给定二叉搜索树的根结点 root
,返回值位于范围 [low, high]
之间的所有结点的值的和。
示例 1:

输入:root = [10,5,15,3,7,null,18], low = 7, high = 15
输出:32
示例 2:

输入:root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
输出:23
提示:
- 树中节点数目在范围
[1, 2 * 104]
内 1 <= Node.val <= 105
1 <= low <= high <= 105
- 所有
Node.val
互不相同
2.基础框架
C++基础框架代码如下:
int rangeSumBST(TreeNode* root, int low, int high) {
}
3.解题思路
- 题目分析
题目目标返回二叉搜索树中值在
[low, high]
的和。二叉搜索树的特点是,左孩子节点的值比父结点小,右孩子结点值比父结点大。
可能存在的情况:
- ①范围在父节点的左侧,总体比父节点小,即
parent > high
,父节点往左孩子遍历 - ②范围在父节点的右侧,总体比父节点大,即
parent < low
,父节点往右孩子遍历 - ③范围在父节点的左右侧,
low
值比父节点小,high
值比父节点大,即low < parent < high
。左右孩子都遍历。
- ①范围在父节点的左侧,总体比父节点小,即
返回的和
sum
应从范围内开始计算。当遇到不满足的情况,即该结点的值不满足
[low, high]
的范围:① 左右孩子也不在
[low,high]
范围中,或者该结点为空的时候,返回0。② 其中有一个孩子存在
[low, high]
范围中,则一直递归孩子方向,直到遇到①的情况,返回0。
- 实现代码:
int rangeSumBST(TreeNode* root, int low, int high) {
if (root == nullptr) return 0;
if (root->val < low)
return rangeSumBST(root->right, low, high);
else if (root->val > high)
return rangeSumBST(root->left, low, high);
else
return rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high) + root->val;
边栏推荐
- 关于Visual Studio 2019的前期详情
- The relevant person in charge of the state Internet Information Office answered reporters' questions on the decision to impose administrative penalties related to network security review on didi Globa
- FPGA设计中遇到的奇葩问题之“芯片也要看出身”(三)
- 互联网和传输层协议
- Postman - post请求application/x-www-from-urlencoded
- Analysis on the characteristics of two-layer industrial switch
- Revit API:EditScope
- Navicate 连接阿里云(两种方式及原理讲解)
- 理财产品到期不赎回会自动续期吗?
- 过D盾php webshell免杀马探讨
猜你喜欢
idea报错Port 8080 is already in use
Openai officially announced that dall-e will open its beta to 1million users
Postman - post请求application/json参数
Idea 连接 MySQL 数据库
Discussion on passing the d-shield PHP webshell without killing horses
Discussion on passing D shield JSP webshell+ ice scorpion avoiding killing horses
Wechat applet_ 19. Custom components -behaviors
免杀exe技术探讨
kali wifi破解(多种方式)
Postman - post请求application/x-www-from-urlencoded
随机推荐
Discussion on passing the d-shield PHP webshell without killing horses
RavenDB完全事务性的 NoSQL 文档数据库
Typora Beta版过期解决
Ravendb fully transactional NoSQL document database
Document operation management
2022年数据库审计产品排行榜-必看!
基于通用单片机(久齐) 半导体制冷制热的控制 手机散热器按摩仪器中冷热头的控制
Kyligence 出席华为全球智慧金融峰会,加速拓展全球市场
仅需一个依赖给Swagger换上新皮肤,既简单又炫酷
Those violations in the store will be punished by the official secondary punishment, the most common four
文件操作管理
数据中心线缆管理
Niuke online question brushing - day 3
金鱼哥RHCA回忆录:CL210集成身份管理--项目组织管理+章节实验
C#. Net sqlserver login function
Zabbix3.0版报警设置
The difference between w3school and w3school
92.(leaflet篇)leaflet态势标绘-进攻方向采集
国家互联网信息办公室对滴滴全球股份有限公司依法作出网络安全审查相关行政处罚的决定
The wonderful problem encountered in FPGA design - "chip also depends on origin" (III)