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

HCIP (01)

HCIA experiment (07) comprehensive experiment

I, AI doctoral student, online crowdfunding research topic

2021 CEC written examination summary

Esp32c3 based on the example tutorial of esp32 Rainmaker development under Arduino framework

HCIA实验(10)NAT

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!

100W!

HCIA experiment (09)

HCIP(11)
随机推荐
Learn NLP with Transformer (Chapter 4)
[flask advanced] deeply understand the application context and request context of flask from the source code
HCIP实验(01)
Use three.js to realize the cool cyberpunk style 3D digital earth large screen
Learn NLP with Transformer (Chapter 6)
Learn NLP with Transformer (Chapter 3)
HCIA experiment (09)
Dataset and dataloader data loading
Electromagnetic field and electromagnetic wave experiment I familiar with the application of MATLAB software in the field of electromagnetic field
[strategic mode] like Zhugeliang's brocade bag
Code representation learning: introduction to codebert and other related models
JS collection
Flask framework - session and cookies
JS hash table 01
为什么重写equals()方法必须要重写hashCode()方法
Flask框架——Flask-WTF表单:文件上传、验证码
Learn NLP with Transformer (Chapter 1)
STM32CubeMX学习记录--安装配置与使用
HCIP(13)
NB-IOT控制液晶屏(日期的设置与读取)