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

Nb-iot control LCD (date setting and reading)

BGP联邦实验

性能测试中TPS的计算【杭州多测师】【杭州多测师_王sir】

学习路之PHP--TP5.0使用中文当别名,报“不支持的数据表达式”

Flask框架——flask-caching缓存
Learn NLP with Transformer (Chapter 2)

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

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

Esp8266 uses drv8833 drive board to drive N20 motor

Reinforcement Learning 强化学习(四)
随机推荐
Guys, flick CDC table API, Mysql to MySQL, an application that can
上周热点回顾(7.18-7.24)
Visual thematic map of American airport go style: ArcGIS Pro version
接口流量突增,如何做好性能调优?
mysql主从复制与读写分离
HCIA experiment (09)
API supplement of JDBC
【高并发】如何实现亿级流量下的分布式限流?这些理论你必须掌握!!
三万字速通Servlet
[domain generalization] 2022 IJCAI domain generalization tutorial Report
HCIP(12)
Signal integrity (SI) power integrity (PI) learning notes (XXXIV) 100 rules of thumb for estimating signal integrity effects
Electromagnetic field and electromagnetic wave experiment I familiar with the application of MATLAB software in the field of electromagnetic field
[flask advanced] combined with the source code, explain the operation mechanism of flask (in and out of the stack)
我,AI博士生,在线众筹研究主题
Code representation learning: introduction to codebert and other related models
HCIA experiment (07) comprehensive experiment
Flask框架——消息闪现
HCIP(13)
The University of Gottingen proposed clipseg: a model that can perform three segmentation tasks simultaneously using text and image prompts