当前位置:网站首页>[recursion] 938. Range and of binary search tree
[recursion] 938. Range and of binary search tree
2022-07-25 11:23:00 【fatfatmomo】
Given the root of the binary search tree root, return L and R( contain ) The sum of the values of all nodes between ( In the tree X>=L&&X<=R Of X It's worth it and ).
Initial solution , All traversal recursion
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;
}
};
Another kind of recursion , The time is a little longer than the above .
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);
}
};
边栏推荐
猜你喜欢
随机推荐
[high concurrency] how to realize distributed flow restriction under 100 million level traffic? You must master these theories!!
shell-第四天作业
LVS负载均衡之LVS-NAT与LVS-DR模式原理详解
NowCoderTOP1-6——持续更新ing
Understand the life cycle and route jump of small programs
MLX90640 红外热成像仪测温模块开发笔记(五)
Reinforcement learning (III)
一篇看懂:IDEA 使用scala 编写wordcount程序 并生成jar包 实测
MLX90640 红外热成像仪测温模块开发笔记(五)
[flask advanced] deeply understand the application context and request context of flask from the source code
The B2B2C multi merchant system has rich functions and is very easy to open!!!
SQL语言(五)
Nb-iot control LCD (date setting and reading)
Learn NLP with Transformer (Chapter 2)
Reinforcement Learning 强化学习(三)
ESP8266 使用 DRV8833驱动板驱动N20电机
Some usages of beautifulsoup
DICOM medical image viewing and browsing function based on cornerstone.js
Signal integrity (SI) power integrity (PI) learning notes (XXXIV) 100 rules of thumb for estimating signal integrity effects
信息熵的定义








