当前位置:网站首页>[递归] 938. 二叉搜索树的范围和
[递归] 938. 二叉搜索树的范围和
2022-07-25 10:27:00 【fatfatmomo】
给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和(即树中 X>=L&&X<=R 的X值的和)。
初始解法,全部遍历递归
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
int sum=0;
if(root->val>=L&&root->val<=R)
{
sum+=root->val;
}
if(root->left!=nullptr)
{
sum+=rangeSumBST(root->left,L,R);
}
if(root->right!=nullptr)
{
sum+=rangeSumBST(root->right,L,R);
}
return sum;
}
};
另一种递归,时间反而比上面的长一点。
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
if(root==nullptr)
{
return 0;
}
if(root->val<L)
{
return rangeSumBST(root->right,L,R);
}
if(root->val>R)
{
return rangeSumBST(root->left,L,R);
}
return root->val+rangeSumBST(root->right,L,R)+rangeSumBST(root->left,L,R);
}
};
边栏推荐
- Learn NLP with Transformer (Chapter 7)
- mysql事务是什么
- HCIA experiment (10) nat
- 软件测试技术之跨平台的移动端UI自动化测试(上)
- Google Earth engine -- Statistics on the frequency of land classification year by year
- Guys, flick CDC table API, Mysql to MySQL, an application that can
- 信号完整性(SI)电源完整性(PI)学习笔记(三十四)100条估计信号完整性效应的经验法则
- Understand the life cycle and route jump of small programs
- 接口流量突增,如何做好性能调优?
- Flask框架——消息闪现
猜你喜欢
![[Blue Bridge Cup training 100 questions] scratch Taiji diagram Blue Bridge Cup scratch competition special prediction programming question centralized training simulation exercise question No. 22](/img/d5/56173050f62d5b6fa336ff8d257fca.png)
[Blue Bridge Cup training 100 questions] scratch Taiji diagram Blue Bridge Cup scratch competition special prediction programming question centralized training simulation exercise question No. 22

JS collection

HCIA experiment (08)

Learn NLP with Transformer (Chapter 5)

mysql主从复制与读写分离

UE4 framework introduction

哥廷根大学提出CLIPSeg:一个使用文本和图像prompt能同时作三个分割任务的模型

Reinforcement Learning 强化学习(四)

MySQL master-slave replication and read-write separation

Ue4.26 source code version black screen problem of client operation when learning Wan independent server
随机推荐
【云享新鲜】社区周刊·Vol.72- 2022华为开发者大赛中国区首场开幕式启动;华为云KooMessage火热公测中…
机智云物联网平台 STM32 ESP8266-01S 简单无线控灯
API supplement of JDBC
Redis sentry, high availability executor
接口流量突增,如何做好性能调优?
为什么重写equals()方法必须要重写hashCode()方法
HCIA实验(06)
Flask框架——Flask-WTF表单:文件上传、验证码
Basic experiment of microwave technology - Filter Design
BGP federal experiment
Dataset and dataloader data loading
最详细的mysql索引解析(文末附赠思维导图)
Learn NLP with Transformer (Chapter 7)
Digital twin everything can be seen | connecting the real world and digital space
树形动态规划
From the perspective of open source, analyze the architecture design of SAP classic ERP that will not change in 30 years
【IJCAI 2022】参数高效的大模型稀疏训练方法,大幅减少稀疏训练所需资源
JS collection
Learn NLP with Transformer (Chapter 8)
HCIP(12)