当前位置:网站首页>[递归] 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);
}
};
边栏推荐
猜你喜欢

Electromagnetic field and electromagnetic wave experiment I familiar with the application of MATLAB software in the field of electromagnetic field

Reinforcement Learning 强化学习(四)
Learn NLP with Transformer (Chapter 4)

2021 qunar written examination summary

NB-IOT控制液晶屏(日期的设置与读取)

The idea has been perfectly verified again! The interest rate hike is approaching, and the trend is clear. Take advantage of this wave of market!

mysql高级语句(一)(总有一个人的出现,让你的生活不再继续糟糕)

【flask高级】从源码深入理解flask的应用上下文和请求上下文

BGP federal experiment
Learn NLP with Transformer (Chapter 2)
随机推荐
[flask advanced] solve the classic error reporting of flask by combining the source code: working outside of application context
30000 word express Servlet
PostgreSQL踩坑 | ERROR: operator does not exist: uuid = character varying
HCIP(13)
Hcip experiment (01)
Hcip experiment (03)
【域泛化】2022 IJCAI领域泛化教程报告
NowCoderTOP1-6——持续更新ing
2021 scenery written examination summary
机智云物联网平台 STM32 ESP8266-01S 简单无线控灯
MySQL | GROUP_CONCAT函数,将某一列的值用逗号拼接
Flask框架——flask-caching缓存
Flask框架——Flask-WTF表单:文件上传、验证码
HCIP (01)
I, AI doctoral student, online crowdfunding research topic
Disabled and readonly and focus issues
史上最全的立创元器件封装库导入AD详细教程(一直白嫖一直爽)
mysql高级语句(一)(总有一个人的出现,让你的生活不再继续糟糕)
Ue4.26 source code version black screen problem of client operation when learning Wan independent server
Electromagnetic field and electromagnetic wave experiment I familiar with the application of MATLAB software in the field of electromagnetic field