当前位置:网站首页>[递归] 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);
}
};
边栏推荐
- 基于cornerstone.js的dicom医学影像查看浏览功能
- Hcip experiment (04)
- C# Newtonsoft.Json 高级用法
- 最详细的mysql索引解析(文末附赠思维导图)
- Learn NLP with Transformer (Chapter 8)
- [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
- 30000 word express Servlet
- JS bidirectional linked list 02
- Google Earth engine -- Statistics on the frequency of land classification year by year
- Learn NLP with Transformer (Chapter 7)
猜你喜欢

Flask framework -- flask caching

Flask框架——Flask-WTF表单:文件上传、验证码

MLX90640 红外热成像仪测温模块开发笔记(五)

100W!
![[flask advanced] solve the classic error reporting of flask by combining the source code: working outside of application context](/img/3e/2cc3ff7e6e45ba4fcf3a0f5c2bf478.png)
[flask advanced] solve the classic error reporting of flask by combining the source code: working outside of application context

HCIP (01)
Learn NLP with Transformer (Chapter 4)

HCIA实验(07)综合实验

Learn NLP with Transformer (Chapter 1)

【flask高级】从源码深入理解flask的应用上下文和请求上下文
随机推荐
JS bidirectional linked list 02
2021 qunar written examination summary
Flask框架——flask-caching缓存
Learn NLP with Transformer (Chapter 2)
MySQL master-slave replication and read-write separation
从开源的视角,解析SAP经典ERP “三十年不用变”的架构设计
HCIA experiment (09)
【Servlet】请求的解析
Ue4.26 source code version black screen problem of client operation when learning Wan independent server
mysql事务是什么
【高并发】如何实现亿级流量下的分布式限流?这些理论你必须掌握!!
Last week's hot review (7.18-7.24)
B2B2C多商户系统功能丰富,极易二开!!!
Flask框架——消息闪现
JDBC的APi补充
Hcip experiment (04)
30000 word express Servlet
Flask framework - session and cookies
MySQL advanced statement (I) (there is always someone who will make your life no longer bad)
HCIP(11)