question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
find-valid-emails
|
SQL || easy solution
|
sql-easy-solution-by-thamaraiselvi05-hw71
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
ThamaraiSelvi05
|
NORMAL
|
2025-02-08T13:31:02.700971+00:00
|
2025-02-08T13:31:02.700971+00:00
| 15 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```mysql []
# Write your MySQL query statement below
select user_id,email from Users
where email like "%@%.com"
order by user_id;
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
[MySQL] Good enough
|
mysql-good-enough-by-parrotypoisson-h6ly
| null |
parrotypoisson
|
NORMAL
|
2025-02-07T16:40:37.327072+00:00
|
2025-02-07T16:40:37.327072+00:00
| 13 | false |
```mysql []
# Write your MySQL query statement below
SELECT *
FROM Users
WHERE email REGEXP '[a-zA-Z0-9_]+@[a-zA-Z]+\.com'
ORDER BY user_id;
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
Pandas regex users.email.str.match('xxxx')
|
pandas-regex-usersemailstrmatchxxxx-by-n-vfzi
|
Code
|
nanzhuangdalao
|
NORMAL
|
2025-02-06T23:47:53.514623+00:00
|
2025-02-06T23:48:53.166698+00:00
| 11 | false |
# Code
```pythondata []
import pandas as pd
def find_valid_emails(users: pd.DataFrame) -> pd.DataFrame:
df = users[users.email.str.match('\w+@[a-zA-Z]+\.com')]
return df.sort_values(by = 'user_id')
```
| 0 | 0 |
['Pandas']
| 0 |
find-valid-emails
|
MySQL where regexp_like(email, 'xxxxxx')
|
mysql-where-regexp_likeemail-xxxxxx-by-n-bzvk
|
Code
|
nanzhuangdalao
|
NORMAL
|
2025-02-06T22:28:25.129544+00:00
|
2025-02-06T22:47:49.078753+00:00
| 8 | false |
# Code
```mysql []
# Write your MySQL query statement below
select user_id, email
from users
where regexp_like(email, '[a-zA-Z0-9_]+@[a-zA-Z]+\.com
```)
order by user_id
```
```mysql []
# Write your MySQL query statement below
select user_id, email
from users
where regexp_like(email, '\\w+@[a-zA-Z]+\.com$')
order by user_id
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
Easy Pandas solution using REGEX | Beats 87.84%
|
easy-pandas-solution-using-regex-beats-8-bs03
|
IntuitionUsing a regular expression to filter the rows with appropriate string values in the email column.ApproachComplexity
Time complexity:
345ms
Space com
|
Himanshu_soni2023
|
NORMAL
|
2025-02-06T17:18:32.168104+00:00
|
2025-02-06T17:18:32.168104+00:00
| 14 | false |
# Intuition
Using a regular expression to filter the rows with appropriate string values in the email column.
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
345ms
- Space complexity:
61.18MB
# Code
```pythondata []
import pandas as pd
def find_valid_emails(users: pd.DataFrame) -> pd.DataFrame:
users = users.sort_values(by = 'user_id', ascending = True)
result = users[users['email'].str.contains(r'^[a-zA-Z0-9_]+@[a-zA-Z]+\.com
```)]
# ^[a-zA-Z0-9_]+: This part ensures the email starts with alphanumeric characters or underscores.
# @: There should be exactly one @ symbol.
# ([a-zA-Z]+): After the @ symbol, we ensure only alphabetic characters are allowed in the domain part.
# \.com$: Ensures the email ends with .com.
return result
```
| 0 | 0 |
['Pandas']
| 0 |
find-valid-emails
|
Using REGEXP_LIKE
|
using-regexp_like-by-sktarab4-zblj
|
SELECT *
FROM Users
WHERE REGEXP_LIKE (email,'[a-zA-z0-9]+@[a-zA-Z]+.com')
ORDER BY user_id;
|
sktarab4
|
NORMAL
|
2025-02-06T16:19:55.358724+00:00
|
2025-02-06T16:19:55.358724+00:00
| 12 | false |
SELECT *
FROM Users
WHERE REGEXP_LIKE (email,'[a-zA-z0-9]+@[a-zA-Z]+\.com')
ORDER BY user_id;
| 0 | 0 |
['PostgreSQL']
| 0 |
find-valid-emails
|
Easy peasy 😎
|
easy-peasy-by-lalitkp095-ptfu
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
lalitkp095
|
NORMAL
|
2025-02-05T19:52:02.179924+00:00
|
2025-02-05T19:52:02.179924+00:00
| 12 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```mysql []
SELECT *
FROM Users
WHERE email REGEXP '^[A-Za-z0-9]+@[A-Za-z]+.com
``` ;
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
some users may enter capital letters after the @!
|
some-users-may-enter-capital-letters-aft-v3r9
|
Code
|
briansiege
|
NORMAL
|
2025-02-05T18:03:54.709940+00:00
|
2025-02-05T18:04:53.022895+00:00
| 7 | false |
# Code
```mysql []
# Write your MySQL query statement below
select *
from Users
where REGEXP_LIKE(email, '^[a-zA-Z0-9_]*@[a-zA-Z]*.com')
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
Three solutions
|
three-solutions-by-t56ns9jotb-ppym
|
CodeSolution 3
|
t56Ns9joTb
|
NORMAL
|
2025-02-04T22:40:44.243793+00:00
|
2025-02-04T22:40:44.243793+00:00
| 16 | false |
# Code
```pythondata []
import pandas as pd
import re
def find_valid_emails(users: pd.DataFrame) -> pd.DataFrame:
# Solution 1
def is_valid(email):
if '@' not in email or not email.endswith('.com'):
return False
else:
begin, domain = email.split('@')
if not begin.isalnum() or not domain.split('.')[0].isalpha():
return False
return True
# Solution 2: Using regex
def is_valid(email):
pattern = r'^[a-zA-Z0-9]+@[a-zA-Z]+.com
result = re.match(pattern, email)
return bool(result)
return users[users['email'].apply(is_valid)].\
sort_values(by='user_id')
```
# Solution 3
```pythondata []
import pandas as pd
import re
def find_valid_emails(users: pd.DataFrame) -> pd.DataFrame:
pattern = r'^[a-zA-Z0-9]+@[a-zA-Z]+.com'
return users[users['email'].str.contains(pattern)].\
sort_values(by='user_id')
```
| 0 | 0 |
['Pandas']
| 0 |
find-valid-emails
|
Deсшышщт
|
desshyshshcht-by-reshetnikov_dmitrii-l77j
|
Code
|
Reshetnikov_Dmitrii
|
NORMAL
|
2025-02-04T20:57:52.342485+00:00
|
2025-02-04T20:57:52.342485+00:00
| 25 | false |
# Code
```mssql []
/* Write your T-SQL query statement below */
SELECT * FROM Users WHERE email LIKE '%.com' and email LIKE '%@%' and LEFT(email, CHARINDEX('@', email + '@') - 1) NOT LIKE '%[^a-zA-Z0-9]%'
order by user_id
```
| 0 | 0 |
['MS SQL Server']
| 0 |
find-valid-emails
|
Regexp
|
regexp-by-sumeetrayat-8qov
|
Code
|
sumeetrayat
|
NORMAL
|
2025-02-04T16:33:24.569363+00:00
|
2025-02-04T16:33:24.569363+00:00
| 40 | false |
# Code
```mysql []
# Write your MySQL query statement below
select * from Users where email REGEXP '^[a-zA-Z0-9]+@[a-zA-Z]+.com
``` order by user_id
```
| 0 | 0 |
['MySQL']
| 1 |
find-valid-emails
|
valid emails
|
valid-emails-by-vikas98sss-ou4t
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
vikas98sss
|
NORMAL
|
2025-02-04T07:17:14.433487+00:00
|
2025-02-04T07:17:14.433487+00:00
| 13 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```mysql []
# Write your MySQL query statement below
select user_id,email
from users
where regexp_like(email,'[a-zA-Z0-9_]+@[a-zA-Z0-9_]+\.com
```)
order by user_id
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
find-valid-emails(mysql)
|
find-valid-emailsmysql-by-sssanskarrr-he7s
|
SELECT * FROM Users WHERE email LIKE "%@%.com";
|
sssanskarrr
|
NORMAL
|
2025-02-04T05:47:32.701398+00:00
|
2025-02-04T05:47:32.701398+00:00
| 11 | false |
SELECT * FROM Users WHERE email LIKE "%@%.com";
| 0 | 0 |
['Database', 'MySQL']
| 0 |
find-valid-emails
|
Solution with re
|
solution-with-re-by-inveterate_enthusias-q51s
|
Code on PythonCode on PostgreSQL
|
Inveterate_Enthusiast
|
NORMAL
|
2025-02-04T05:13:55.259363+00:00
|
2025-02-04T05:13:55.259363+00:00
| 18 | false |
# Code on Python
```python
import pandas as pd
import re
def find_valid_emails(users: pd.DataFrame) -> pd.DataFrame:
pattern = r"\w+\@[^\W\d_]+\.com"
users["bool"] = users["email"].apply(lambda x: True if re.findall(pattern, x) else False)
return users.loc[users["bool"]].drop(labels="bool", axis=1).sort_values(by="user_id", ascending=True)
```
---
# Code on PostgreSQL
```postgresql []
-- Write your PostgreSQL query statement below
SELECT
*
FROM Users
WHERE email ~ '\w+\@[^\W\d_]+\.com'
ORDER BY user_id ASC;
```
| 0 | 0 |
['Python3', 'PostgreSQL', 'Pandas']
| 0 |
find-valid-emails
|
Pandas
|
pandas-by-longmen-93ia
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Codedef find_valid_emails(users: pd.DataFrame) -> pd.DataFrame:
users['is_valid'] = users['email
|
longmen
|
NORMAL
|
2025-02-04T00:33:59.287978+00:00
|
2025-02-04T00:33:59.287978+00:00
| 9 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```pythondata []
import pandas as pd
import re
def is_valid_email(email: str) -> bool:
pattern = r'^[\w]+@[a-zA-Z]+\.(com)
```
return bool(re.match(pattern, email))
def find_valid_emails(users: pd.DataFrame) -> pd.DataFrame:
users['is_valid'] = users['email'].apply(is_valid_email)
valid_emails = users[users['is_valid']]
valid_emails_sorted = valid_emails.sort_values(by='user_id')
valid_emails_sorted = valid_emails_sorted.drop(columns=['is_valid'])
return valid_emails_sorted
```
| 0 | 0 |
['Pandas']
| 0 |
find-valid-emails
|
SQL
|
sql-by-johnmullan-9tic
|
Code
|
JohnMullan
|
NORMAL
|
2025-02-03T22:53:48.194780+00:00
|
2025-02-03T22:53:48.194780+00:00
| 13 | false |
# Code
```mysql []
# Write your MySQL query statement below
SELECT *
FROM Users
WHERE email REGEXP "^[0-9a-zA-Z]*@[a-zA-Z]*.com"
ORDER BY user_id ASC
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
find valid emails
|
find-valid-emails-by-amitkumar33-oghe
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
Amitkumar33
|
NORMAL
|
2025-02-02T07:17:28.861472+00:00
|
2025-02-02T07:17:28.861472+00:00
| 21 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```mysql []
# Write your MySQL query statement below
SELECT user_id,
email
FROM users
WHERE regexp_like(email, '[a-zA-Z0-9_]+@[a-zA-Z0-9_]+\.com
```)
ORDER BY user_id;
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
Easy MS SQL Server Solution Using RIGHT + LEN + PATINDEX
|
easy-ms-sql-server-solution-using-right-g9rms
|
Code
|
Vaishnav-Dahake
|
NORMAL
|
2025-02-02T00:22:37.257446+00:00
|
2025-02-02T00:25:33.951596+00:00
| 38 | false |
# Code
```mssql []
SELECT user_id , email
FROM Users
WHERE RIGHT(email,4) = '.com' and LEN(email) - LEN(REPLACE(email,'@','')) = 1 and
PATINDEX('%[^a-zA-Z0-9_]%@%',email) = 0 and PATINDEX('%@%[^a-zA-Z]%.com%',email) = 0
```
| 0 | 0 |
['Database', 'MS SQL Server']
| 0 |
find-valid-emails
|
✅ Simple and straightforward, 100% ✅
|
simple-and-straightforward-100-by-stefan-1mdv
|
ExplanationSimple query using LIKE operator and functions CHAR_LENGTH and REPLACE.There are 2 parts here:
email like '%.com' matches all values ending in .com.
|
StefanEvanghelides
|
NORMAL
|
2025-02-01T22:22:04.126530+00:00
|
2025-02-01T22:22:04.126530+00:00
| 26 | false |
# Explanation
Simple query using `LIKE` operator and functions `CHAR_LENGTH` and `REPLACE`.
There are 2 parts here:
- `email like '%.com'` matches all values ending in `.com`.
- `(CHAR_LENGTH(email) - CHAR_LENGTH(REPLACE(email, '@', ''))) = 1` can be split as follows:
- the diff between the size of the column and the size of the column, assuming all chars `@` are removed. This effectively gives us the count of `@` characters.
- finally, we want this count to be 1, so that we only allow emails that have exactly 1 `@` character.
# Code
```postgresql []
-- Write your PostgreSQL query statement below
select * from Users where email like '%.com' and (CHAR_LENGTH(email) - CHAR_LENGTH(REPLACE(email, '@', ''))) = 1
```
| 0 | 0 |
['PostgreSQL']
| 0 |
find-valid-emails
|
LIKE operator
|
like-operator-by-jai19112004-ukly
|
Code
|
ManasKhudale
|
NORMAL
|
2025-02-01T10:57:59.666137+00:00
|
2025-02-01T10:57:59.666137+00:00
| 25 | false |
# Code
```mysql []
# Write your MySQL query statement below
SELECT * FROM Users WHERE email LIKE "%@%.com";
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
Simple MySQL Solution
|
simple-mysql-solution-by-sakshikishore-8ltw
|
Code
|
sakshikishore
|
NORMAL
|
2025-02-01T06:04:24.403182+00:00
|
2025-02-01T06:04:24.403182+00:00
| 20 | false |
# Code
```mysql []
# Write your MySQL query statement below
SELECT * FROM Users WHERE email REGEXP '^[a-zA-Z0-9_]+@[a-zA-Z]+.com
ORDER by user_id
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
Slay Email Demons with Regex Beats 96.69%
|
slay-email-demons-with-regex-beats-9669-cjtim
|
IntuitionThis is a classic regex problem. Despite the arcane syntax, it is the most concise way to solve these types of problems.ApproachGiven constraints, we w
|
wavejumper45
|
NORMAL
|
2025-02-01T05:44:05.845839+00:00
|
2025-02-01T05:44:43.938352+00:00
| 8 | false |
# Intuition
This is a classic regex problem. Despite the arcane syntax, it is the most concise way to solve these types of problems.
# Approach
Given constraints, we want to use Extended Regex (including the + which is equivalent to 1-or-more-occurences).
The username must contain alnum (lower/upper/numeral) at least one character (and excepting the '@' symbol).
The domain name must contain alpha at least one character (you are worth millions if you have one of those one character dotcom domains lol) (and excepting the '@' symbol).
Then ending in '.com' literally with end of string.
# Code
```mysql []
# Write your MySQL query statement below
SELECT *
FROM Users
WHERE REGEXP_LIKE(email, '[a-zA-Z0-9^@]+@[a-zA-Z^@]+\.com$')
ORDER BY user_id
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
Simple Approach
|
simple-approach-by-selva-it21-abc3
|
Simple ApproachIn Question it contains many constrains but in testcase doesn't meet the constrains. Refer the code I used to solve this probelmCode
|
selva-it21
|
NORMAL
|
2025-01-31T16:34:44.533025+00:00
|
2025-01-31T16:34:44.533025+00:00
| 175 | false |
# Simple Approach
<!-- Describe your approach to solving the problem. -->
In Question it contains many constrains but in testcase doesn't meet the constrains. Refer the code I used to solve this probelm
# Code
```mysql []
# Write your MySQL query statement below
select user_id, email from Users
where email like '%.com' and email like '%@%'
order by user_id
```
| 0 | 0 |
['MySQL']
| 2 |
find-valid-emails
|
GGez
|
ggez-by-piafyoyo06-wop2
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
CodeORDER BY user_id ASC;
|
piafyoyo06
|
NORMAL
|
2025-01-31T09:10:05.757601+00:00
|
2025-01-31T09:10:05.757601+00:00
| 17 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```mysql []
# Write your MySQL query statement below
SELECT
user_id,
email
FROM Users
WHERE email REGEXP '^[0-9A-Za-z_]+@[A-Za-z]+\\.com
```
ORDER BY user_id ASC;
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
SQL EASY
|
sql-easy-by-pramodamangalagond-gbw7
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
PramodaMangalaGond
|
NORMAL
|
2025-01-31T02:34:11.681201+00:00
|
2025-01-31T02:34:11.681201+00:00
| 26 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```mysql []
# Write your MySQL query statement below
select user_id, email
from users
where email regexp "^[a-zA-Z0-9_]+@[a-zA-z]+\\.com"
order by user_id ;
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
SQL EASY
|
sql-easy-by-pramodamangalagond-229m
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
PramodaMangalaGond
|
NORMAL
|
2025-01-31T02:34:10.403750+00:00
|
2025-01-31T02:34:10.403750+00:00
| 21 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```mysql []
# Write your MySQL query statement below
select user_id, email
from users
where email regexp "^[a-zA-Z0-9_]+@[a-zA-z]+\\.com"
order by user_id ;
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
SQL EASY
|
sql-easy-by-pramodamangalagond-b9n8
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
PramodaMangalaGond
|
NORMAL
|
2025-01-31T02:34:09.863932+00:00
|
2025-01-31T02:34:09.863932+00:00
| 11 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```mysql []
# Write your MySQL query statement below
select user_id, email
from users
where email regexp "^[a-zA-Z0-9_]+@[a-zA-z]+\\.com"
order by user_id ;
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
SQL EASY
|
sql-easy-by-pramodamangalagond-mpz4
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
PramodaMangalaGond
|
NORMAL
|
2025-01-31T02:34:09.197611+00:00
|
2025-01-31T02:34:09.197611+00:00
| 10 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```mysql []
# Write your MySQL query statement below
select user_id, email
from users
where email regexp "^[a-zA-Z0-9_]+@[a-zA-z]+\\.com"
order by user_id ;
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
SQL EASY
|
sql-easy-by-pramodamangalagond-5eof
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
PramodaMangalaGond
|
NORMAL
|
2025-01-31T02:34:08.508245+00:00
|
2025-01-31T02:34:08.508245+00:00
| 4 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```mysql []
# Write your MySQL query statement below
select user_id, email
from users
where email regexp "^[a-zA-Z0-9_]+@[a-zA-z]+\\.com"
order by user_id ;
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
SQL EASY
|
sql-easy-by-pramodamangalagond-8r0l
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
PramodaMangalaGond
|
NORMAL
|
2025-01-31T02:34:07.438933+00:00
|
2025-01-31T02:34:07.438933+00:00
| 6 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```mysql []
# Write your MySQL query statement below
select user_id, email
from users
where email regexp "^[a-zA-Z0-9_]+@[a-zA-z]+\\.com"
order by user_id ;
```
| 0 | 0 |
['MySQL']
| 1 |
find-valid-emails
|
SQL EASY
|
sql-easy-by-pramodamangalagond-x421
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
PramodaMangalaGond
|
NORMAL
|
2025-01-31T02:34:06.110776+00:00
|
2025-01-31T02:34:06.110776+00:00
| 4 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```mysql []
# Write your MySQL query statement below
select user_id, email
from users
where email regexp "^[a-zA-Z0-9_]+@[a-zA-z]+\\.com"
order by user_id ;
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
SQL EASY
|
sql-easy-by-pramodamangalagond-j2zy
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
PramodaMangalaGond
|
NORMAL
|
2025-01-31T02:34:04.637247+00:00
|
2025-01-31T02:34:04.637247+00:00
| 6 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```mysql []
# Write your MySQL query statement below
select user_id, email
from users
where email regexp "^[a-zA-Z0-9_]+@[a-zA-z]+\\.com"
order by user_id ;
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
My Solution
|
my-solution-by-hope_ma-sun3
| null |
hope_ma
|
NORMAL
|
2025-01-30T23:51:55.159413+00:00
|
2025-01-30T23:51:55.159413+00:00
| 12 | false |
```
# Write your MySQL query statement below
SELECT
user_id,
email
FROM
Users
WHERE
-- the email contains exactly one @ symbol
INSTR(email, '@') <> 0 AND
-- the email ends with .com
LOWER(SUBSTR(email, LENGTH(email) - 3, 4)) = '.com' AND
-- the part before the @ symbol contains only alphanumeric characters and underscores
REGEXP_LIKE(LOWER(SUBSTR(email, 1, INSTR(email, '@') - 1)), '[a-z_0-9]') AND
-- the part after the @ symbol and before .com contains a domain name that contains only letters.
REGEXP_LIKE(LOWER(SUBSTR(email, INSTR(email, '@') + 1, LENGTH(email) - 4 - INSTR(email, '@'))), '[a-z]');
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
MYSQL REGEXP_LIKE
|
mysql-regexp_like-by-greg_savage-h34a
|
The first matcher is for the first half. the second, the second half. The last is for no duplicate @ symbols.Code
|
greg_savage
|
NORMAL
|
2025-01-30T17:16:49.617920+00:00
|
2025-01-30T17:17:38.684884+00:00
| 19 | false |
The first matcher is for the first half. the second, the second half. The last is for no duplicate @ symbols.
# Code
```mysql []
SELECT *
FROM Users
WHERE
regexp_like(email, '^[a-zA-Z0-9]+@')
AND regexp_like(email, '@[a-zA-Z].*\\.com$')
and NOT regexp_like(email, '.*@.*@.*')
ORDER BY user_id ASC
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
PostgresQL ~
|
postgresql-by-lykos_unleashed-pd33
|
Code
|
Lykos_unleashed
|
NORMAL
|
2025-01-30T12:22:55.615955+00:00
|
2025-01-30T12:22:55.615955+00:00
| 14 | false |
# Code
```postgresql []
SELECT * FROM Users
Where email ~ '[A-Za-z0-9_]+@[A-Za-z][A-Za-z0-9_]+.com'
```
| 0 | 0 |
['PostgreSQL']
| 0 |
find-valid-emails
|
Find Valid Emails: simple solution using REGEXP. ✅
|
find-valid-emails-simple-solution-using-q7w9v
|
IntuitionThe goal is to identify valid email addresses within a database. A valid email address should contain exactly one @ symbol, with the part before the @
|
rTIvQYSHLp
|
NORMAL
|
2025-01-30T08:28:48.389672+00:00
|
2025-01-30T08:28:48.389672+00:00
| 27 | false |
# Intuition
The goal is to identify valid email addresses within a database. A valid email address should contain exactly one @ symbol, with the part before the @ containing only alphanumeric characters and underscores. The domain part should start with a letter and end with .com.
# Approach
**Pattern:** `^[0-9a-zA-Z_]+@[a-zA-Z][a-zA-Z]*\\.com$`
<br>
- `^` asserts the position at the start of the string. <br>
- `[0-9a-zA-Z_]+` matches one or more alphanumeric characters or underscores before the `@` symbol. <br>
- `@` matches the `@` symbol exactly. <br>
- `[a-zA-Z]` ensures that the domain part starts with a letter. <br>
- `[a-zA-Z]*` matches zero or more letters following the initial letter in the domain. <br>
- `\.com` matches the exact string `.com`. <br>
- `$` asserts the position at the end of the string.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```mysql []
# Write your MySQL query statement below
select *
from Users
where email regexp '^[0-9a-zA-Z_]+@[a-zA-Z][a-zA-Z]*\\.com
```
order by user_id
```
| 0 | 0 |
['MySQL']
| 0 |
find-valid-emails
|
SQL
|
sql-by-janhavi2011-ktre
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Codeorder by user_id ASC;
|
Janhavi2011
|
NORMAL
|
2025-01-30T07:22:16.515151+00:00
|
2025-01-30T07:22:16.515151+00:00
| 32 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```mysql []
# Write your MySQL query statement below
Select user_id ,email from Users
where email REGEXP '^[a-zA-z0-9]+@[a-zA-z][a-zA-Z0-9]*\\.com
```
order by user_id ASC;
```
| 0 | 0 |
['MySQL']
| 0 |
range-sum-of-bst
|
[Java/Python 3] 3 similar recursive and 1 iterative methods w/ comment & analysis.
|
javapython-3-3-similar-recursive-and-1-i-t3a8
|
Three similar recursive and one iterative methods, choose one you like.\n\nMethod 1:\n\n public int rangeSumBST(TreeNode root, int L, int R) {\n if (r
|
rock
|
NORMAL
|
2018-11-11T04:02:09.068555+00:00
|
2022-12-08T06:41:55.291167+00:00
| 69,006 | false |
Three similar recursive and one iterative methods, choose one you like.\n\n**Method 1:**\n```\n public int rangeSumBST(TreeNode root, int L, int R) {\n if (root == null) return 0; // base case.\n if (root.val < L) return rangeSumBST(root.right, L, R); // left branch excluded.\n if (root.val > R) return rangeSumBST(root.left, L, R); // right branch excluded.\n return root.val + rangeSumBST(root.right, L, R) + rangeSumBST(root.left, L, R); // count in both children.\n }\n```\n```\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n if not root:\n return 0\n elif root.val < L:\n return self.rangeSumBST(root.right, L, R)\n elif root.val > R:\n return self.rangeSumBST(root.left, L, R)\n return root.val + self.rangeSumBST(root.left, L, R) + self.rangeSumBST(root.right, L, R)\n```\nThe following are two more similar recursive codes.\n\n**Method 2:**\n```\n public int rangeSumBST(TreeNode root, int L, int R) {\n if (root == null) return 0; // base case.\n return (L <= root.val && root.val <= R ? root.val : 0) + rangeSumBST(root.right, L, R) + rangeSumBST(root.left, L, R);\n }\n```\n```\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n if not root:\n return 0\n return self.rangeSumBST(root.left, L, R) + \\\n self.rangeSumBST(root.right, L, R) + \\\n (root.val if L <= root.val <= R else 0)\n```\n**Method 3:**\n```\n public int rangeSumBST(TreeNode root, int L, int R) {\n if (root == null) { return 0; }\n int sum = 0;\n if (root.val > L) { sum += rangeSumBST(root.left, L, R); } // left child is a possible candidate.\n if (root.val < R) { sum += rangeSumBST(root.right, L, R); } // right child is a possible candidate.\n if (root.val >= L && root.val <= R) { sum += root.val; } // count root in.\n return sum;\n }\n```\n```\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n if not root:\n return 0\n sum = 0\n if root.val > L:\n sum += self.rangeSumBST(root.left, L, R)\n if root.val < R:\n sum += self.rangeSumBST(root.right, L, R)\n if L <= root.val <= R:\n sum += root.val \n return sum\n```\n\n**Method 4: Iterative version**\n```\n public int rangeSumBST(TreeNode root, int L, int R) {\n Stack<TreeNode> stk = new Stack<>();\n stk.push(root);\n int sum = 0;\n while (!stk.isEmpty()) {\n TreeNode n = stk.pop();\n if (n == null) { continue; }\n if (n.val > L) { stk.push(n.left); } // left child is a possible candidate.\n if (n.val < R) { stk.push(n.right); } // right child is a possible candidate.\n if (L <= n.val && n.val <= R) { sum += n.val; }\n }\n return sum;\n }\n```\n```\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n stk, sum = [root], 0\n while stk:\n node = stk.pop()\n if node:\n if node.val > L:\n stk.append(node.left) \n if node.val < R:\n stk.append(node.right)\n if L <= node.val <= R:\n sum += node.val \n return sum\n```\n**Analysis:**\n\nAll 4 methods will DFS traverse all nodes in worst case, and if we count in the recursion trace space cost, the complexities are as follows:\n\n**Time: O(n), space: O(h)**, where `n` is the number of total nodes, `h` is the height of the tree..
| 443 | 8 |
['Java', 'Python3']
| 44 |
range-sum-of-bst
|
Java 4 lines Beats 100%
|
java-4-lines-beats-100-by-gordchan-8pbc
|
\n public int rangeSumBST(TreeNode root, int L, int R) {\n if(root == null) return 0;\n if(root.val > R) return rangeSumBST(root.left, L, R);\n
|
gordchan
|
NORMAL
|
2018-12-14T17:34:17.486770+00:00
|
2018-12-14T17:34:17.486837+00:00
| 21,179 | false |
```\n public int rangeSumBST(TreeNode root, int L, int R) {\n if(root == null) return 0;\n if(root.val > R) return rangeSumBST(root.left, L, R);\n if(root.val < L) return rangeSumBST(root.right, L, R);\n return root.val + rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R); \n }\n```
| 136 | 4 |
[]
| 23 |
range-sum-of-bst
|
✅99.43%🔥Easy Solution🔥With Explanation🔥
|
9943easy-solutionwith-explanation-by-mra-ecci
|
Intuition\n#### The problem requires finding the sum of values of all nodes in a binary search tree (BST) that fall within a specified range. Since it\'s a BST,
|
MrAke
|
NORMAL
|
2024-01-08T00:09:29.122820+00:00
|
2024-01-08T02:12:51.023579+00:00
| 29,831 | false |
# Intuition\n#### The problem requires finding the sum of values of all nodes in a binary search tree (BST) that fall within a specified range. Since it\'s a BST, we can take advantage of its properties to efficiently identify the nodes within the given range.\n---\n\n# Approach\n#### To solve this problem, we can perform a depth-first search (DFS) traversal of the BST. At each node, we check whether its value falls within the specified range [low, high]. If the current node\'s value is within the range, we include it in the sum. We then recursively traverse the left and right subtrees.\n\n### The algorithm follows these steps:\n\n#### 1. If the current node is null, return 0.\n#### 2. If the current node\'s value is within the range [low, high], include it in the sum; otherwise, exclude it.\n#### 3. Recursively calculate the sum for the left subtree and the sum for the right subtree.\n#### 4. Return the sum of the current node, left subtree sum, and right subtree sum.\n\n---\n# Complexity\n- ## Time complexity:\n#### $$O(n)$$, where n is the number of nodes in the tree. In the worst case, we may need to visit all nodes in the tree.\n\n- ## Space complexity:\n#### $$O(h)$$, where h is the height of the tree. This represents the maximum depth of the recursive call stack. In the worst case, for an unbalanced tree, the space complexity can be $$O(n)$$, but for a balanced tree, it is $$O(log n)$$.\n---\n# Code\n```python []\nclass Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n def dfs(node):\n if not node:\n return 0\n \n current_val = 0\n if low <= node.val <= high:\n current_val = node.val\n \n left_sum = dfs(node.left)\n right_sum = dfs(node.right)\n \n return current_val + left_sum + right_sum\n \n return dfs(root)\n```\n```java []\npublic class Solution {\n public int rangeSumBST(TreeNode root, int low, int high) {\n if (root == null) {\n return 0;\n }\n\n int currentVal = (root.val >= low && root.val <= high) ? root.val : 0;\n\n int leftSum = rangeSumBST(root.left, low, high);\n int rightSum = rangeSumBST(root.right, low, high);\n\n return currentVal + leftSum + rightSum;\n }\n}\n```\n```javascript []\nvar rangeSumBST = function(root, low, high) {\n if (!root) {\n return 0;\n }\n\n const currentVal = (root.val >= low && root.val <= high) ? root.val : 0;\n\n const leftSum = rangeSumBST(root.left, low, high);\n const rightSum = rangeSumBST(root.right, low, high);\n\n return currentVal + leftSum + rightSum;\n};\n```\n```C++ []\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int low, int high) {\n if (!root) {\n return 0;\n }\n \n int currentVal = (root->val >= low && root->val <= high) ? root->val : 0;\n \n int leftSum = rangeSumBST(root->left, low, high);\n int rightSum = rangeSumBST(root->right, low, high);\n \n return currentVal + leftSum + rightSum;\n }\n};\n```\n```C# []\npublic class Solution {\n public int RangeSumBST(TreeNode root, int low, int high) {\n if (root == null) {\n return 0;\n }\n\n int currentVal = (root.val >= low && root.val <= high) ? root.val : 0;\n\n int leftSum = RangeSumBST(root.left, low, high);\n int rightSum = RangeSumBST(root.right, low, high);\n\n return currentVal + leftSum + rightSum;\n }\n}\n```\n---\n\n\n---
| 133 | 15 |
['Tree', 'Depth-First Search', 'Binary Search Tree', 'Binary Tree', 'C++', 'Java', 'Python3', 'JavaScript', 'C#']
| 15 |
range-sum-of-bst
|
C++ easy explaination Step By Step 100%
|
c-easy-explaination-step-by-step-100-by-ia770
|
\n/*I ll be giving as much details as possible as to what s going on in the recursion stack.\nLets take the binary tree to be [10,5,15,3,7,null,18]\n\t\t\t\t\t\
|
leodicap99
|
NORMAL
|
2020-04-25T06:31:00.445941+00:00
|
2020-04-25T06:31:37.898085+00:00
| 23,845 | false |
```\n/*I ll be giving as much details as possible as to what s going on in the recursion stack.\nLets take the binary tree to be [10,5,15,3,7,null,18]\n\t\t\t\t\t\t\n\t\t\t\t\t\t10\n\t\t\t\t\t\t/\\\n\t\t\t\t\t 5 15\n\t\t\t\t\t /\\ \\\n\t\t\t 3 7 18\ndo your inorder traversal as routine\n sum = 0\n | 3 | \n | 5 | \n | 10 | <-------inorder(root->left)\n |__________|\n we reach the NULL condition of the traversal\n as 3 has no left or right nodes a sum of 0 is passed to 3 3 <-\n / \\ \\\n NULL NULL 0\n 3 is popped out of the stack ans analyzed\n | | 3\n | 5 | \n | 10 | <-------inorder(root->left)\n |__________|\n but as 3 < 7 (L)\n sum value is not changed sum=0\n then 7 is pushed into the stack\n | 7 | \n | 5 | \n | 10 | <-------inorder(root->right)\n |__________|\n as 7 has no leaf nodes inorder(root->left) = NULL\n sum+=7(as 7 is in the range) sum=7\n inorder(root->right) = NULL\n sum=7 is passed to the call stack\n | | 7\n | 5 | \n | 10 | <-------inorder(root->left)\n |__________|\n Now as both the left and right nodes are visited 5 is analyzed.\n inorder(root->left) = 5\n But since 5 is not in the range sum value doesnt change.\n Now 5 is popped out of the stack.\n | | 5 \n | | \n | 10 | <-------inorder(root->left)\n |__________|\n inorder(rot->right) continues excecution.\n | 18 | \n | 15 | \n | 10 | <-------inorder(root->right)\n |__________|\n 18 has no childeren thus sum=7 is passed on to the root.\n 18 is not in the range so sum doesnt change.\n this process continues and 15 gets added to the sum giving sum=22\n then 10 gets added sum=32\n */\n int sum=0;\n int inorder(TreeNode* root,int L,int R)\n {\n if(root){\n inorder(root->left,L,R);\n if(root->val>=L && root->val<=R)\n sum+=root->val;\n inorder(root->right,L,R);\n }\n return sum;\n }\n int rangeSumBST(TreeNode* root, int L, int R) {\n if(!root)return 0;\n return inorder(root,L,R);\n }\n```
| 120 | 15 |
['C', 'C++']
| 25 |
range-sum-of-bst
|
[Python] Simple dfs, explained
|
python-simple-dfs-explained-by-dbabichev-6gpf
|
One way to solve this problem is just iterate over our tree and for each element check if it is range or not. However here we are given, that out tree is BST, t
|
dbabichev
|
NORMAL
|
2020-11-15T11:51:27.603375+00:00
|
2020-11-15T11:51:27.603405+00:00
| 7,955 | false |
One way to solve this problem is just iterate over our tree and for each element check if it is range or not. However here we are given, that out tree is `BST`, that is left subtree is always lesser than node lesser than right subtree. So, let us modify classical `dfs` a bit, where we traverse only nodes we need:\n\n1. Check value `node.val` and if it is in our range, add it to global sum.\n2. We need to visit left subtree only if `node.val > low`, that is if `node.val < low`, it means, that all nodes in left subtree less than `node.val`, that is less than `low` as well.\n3. Similarly, we visit right subtree only if `node.val < high`.\n\n**Complexity**: time complexity is `O(n)`, where `n` is nubmer of nodes in our tree, space complexity potentially `O(n)` as well. We can impove our estimations a bit and say, that time and space is `O(m)`, where `m` is number of nodes in our answer.\n\n```\nclass Solution:\n def rangeSumBST(self, root, low, high):\n def dfs(node):\n if not node: return\n if low <= node.val <= high: self.out += node.val\n if node.val > low: dfs(node.left)\n if node.val < high: dfs(node.right)\n \n self.out = 0\n dfs(root)\n return self.out\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**
| 101 | 2 |
['Depth-First Search']
| 13 |
range-sum-of-bst
|
✅ [C++/Python] Simple Solution w/ Explanation | DFS + BFS w/ Optimizations + O(1) Morris
|
cpython-simple-solution-w-explanation-df-wpkw
|
We are given a BST and range [L, H]. We need to return sum of all nodes between this range.\n\n---\n\n\u2714\uFE0F Solution - I (Simple DFS)\n\nWe can perform a
|
archit91
|
NORMAL
|
2021-12-14T06:08:52.629874+00:00
|
2021-12-14T09:27:20.482433+00:00
| 6,267 | false |
We are given a BST and range `[L, H]`. We need to return sum of all nodes between this range.\n\n---\n\n\u2714\uFE0F ***Solution - I (Simple DFS)***\n\nWe can perform a simple DFS traversal over the tree and if the current node\'s value is within the range `[L, H]`, then we will add it to the final sum. The same process can be carried out recursively till whole tree is explored.\n\n**C++**\n```cpp\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int L, int H) {\n if(!root) return 0;\n return (root -> val >= L && root -> val <= H ? root -> val : 0) + // add root\'s value if it lies within [L, H]\n rangeSumBST(root -> left, L, H) + // recurse left\n rangeSumBST(root -> right, L, H); // recurse right\n }\n};\n```\n\n**Python**\n```python\nclass Solution:\n def rangeSumBST(self, root, L, H):\n if not root: return 0\n return (root.val if root.val >= L and root.val <= H else 0) + \\\n self.rangeSumBST(root.left, L, H) + \\\n self.rangeSumBST(root.right, L, H)\n```\n\n\n***Time Complexity :*** <code>O(N)</code>, where `N` is the number of nodes in the given tree\n***Space Complexity :*** `O(H)`, where `H` is the height of the tree. This is required for recursive stack. In case of skewed tree, this would be `O(N)`, while in case of balanced tree, this would be `O(logN)`\n\n---\n\n\u2714\uFE0F ***Solution - II (BST Optimized DFS)***\n\nIn the above solution, we aren\'t taking the advantage of the fact that our given tree is a BST. We can reduce the search space in some cases by doing conditional recursion. \n* If the root\'s value is less than `L`, then it\'s useless to further recurse the left sub-tree because we know that every node in left sub-tree will be less than `L` as well. **So iterate `root -> left` only when `root -> val > L`**\n* Similarly, if root\'s value is greater than `H`, we must not further recurse the right sub-tree. **So iterate `root -> right` only when `root -> val < H`**\n\nThe above two conditional checks help prune some recursive branches and thus optimize the solution slightly. Note that the time complexity still remains the same as the range can cover all nodes of BST.\n\n**C++**\n```cpp\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int L, int H) {\n if(!root) return 0;\n int ans = root -> val >= L && root -> val <= H ? root -> val : 0;\n if(root -> val > L) ans += rangeSumBST(root -> left, L, H);\n if(root -> val < H) ans += rangeSumBST(root -> right, L, H);\n return ans;\n }\n};\n```\n\n**Python**\n```python\nclass Solution:\n def rangeSumBST(self, root, L, H):\n if not root: return 0\n ans = root.val if root.val >= L and root.val <= H else 0\n if root.val > L: ans += self.rangeSumBST(root.left, L, H)\n if root.val < H: ans += self.rangeSumBST(root.right, L, H)\n return ans\n```\n\n***Time Complexity :*** <code>O(N)</code>, more specifically, this solution would only iterate the nodes which lie within the range `[L, H]`\n***Space Complexity :*** `O(H)`\n\n---\n\n\u2714\uFE0F ***Solution - III (BST Optimized BFS)***\n\nThe same thing can be done using BFS traversal as well. Similar to above approach, we will only push a left or right child into queue if the root\'s value is `> L` or `< H` respectively\n\n**C++**\n```cpp\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* T, int L, int H) {\n queue<TreeNode*> q;\n q.push(T);\n int sum = 0, v;\n while(size(q)) {\n T = q.front(); q.pop();\n v = T -> val;\n if(v >= L and v <= H) sum += v;\n if(v > L && T -> left) q.push(T -> left);\n if(v < H && T -> right) q.push(T -> right);\n }\n return sum;\n }\n};\n```\n\n**Python**\n```python\nclass Solution:\n def rangeSumBST(self, T, L, H):\n q, ans, v = deque([T]), 0, 0\n while q:\n T = q.popleft()\n v = T.val\n if v >= L and v <= H: ans += v\n if v > L and T.left: q.append(T.left)\n if v < H and T.right: q.append(T.right)\n return ans\n```\n\n***Time Complexity :*** <code>O(N)</code>\n***Space Complexity :*** `O(W)`, where `W` is the width of BST. In case of skewed tree, it will be `O(1)` and in case of balanced tree it will be `O(N/2) ~ O(N)`\n\n---\n\n\u2714\uFE0F ***Solution - IV (Morris Traversal)***\n\nWe can also use the Morris traversal (using the inorder version in this case) to optimze on space. I have also made some modification to prune further searches where we know that required node wont be found. You can read more on morris traversal **[here](https://leetcode.com/problems/binary-tree-inorder-traversal/solution/)** and **[here](https://stackoverflow.com/questions/5502916)**.\n\n**C++**\n```cpp\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int L, int H) {\n int ans = 0;\n while(root) \n if(root -> left && root -> val >= L) {\n auto pre = root -> left; \n // finding predecessor of root\n while(pre -> right && pre -> val <= H) pre = pre -> right;\n // make root as right child of predecessor (temporary link)\n pre -> right = root; // adding temporary link\n auto tmp = root;\n root = root -> left; \n tmp -> left = nullptr; // avoiding inifinte loop\n }\n\t\t\telse {\n if(root -> val >= L && root -> val <= H) ans += root -> val;\n if(root -> val < H) root = root -> right;\n else break;\n }\n \n return ans;\n }\n};\n```\n\nThe above version modifies the tree. The following can be used if tree modification is not allowed- \n\n```cpp\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int L, int H) {\n int ans = 0;\n while(root) \n if(root -> left && root -> val >= L) {\n auto pre = root -> left; \n // find predecessor of root\n while(pre -> right && pre -> right != root) pre = pre -> right;\n // make root as right child of predecessor (temporary link)\n if(!pre -> right) {\n pre -> right = root;\n root = root -> left; \n }\n else { \n if(root -> val >= L && root -> val <= H) ans += root -> val;\n pre -> right = nullptr; // revert the changes - remove temporary link\n root = root -> right;\n }\n } \n\t\t\telse {\n if(root -> val >= L && root -> val <= H) ans += root -> val;\n root = root -> right;\n }\n \n return ans;\n }\n};\n```\n\nThe 1st version is optimized to prune redundant search wherever possible, but I guess the 2nd version only prunes left branches. If there\'s a more optimized version of morris traversal that restores the tree as well, do comment below...\n\n***Time Complexity :*** <code>O(N)</code>\n***Space Complexity :*** `O(1)`, only constant space is being used\n\n---\n---\n\n\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, comment below \uD83D\uDC47 \n\n---\n---
| 91 | 2 |
[]
| 13 |
range-sum-of-bst
|
Clean and fast(94%) 4 line Python3 code
|
clean-and-fast94-4-line-python3-code-by-rbp10
|
\nclass Solution:\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n if root == None: return 0\n if root.val > R: return self.ra
|
ypark66
|
NORMAL
|
2019-10-20T05:52:37.609349+00:00
|
2019-10-20T05:54:45.311793+00:00
| 12,104 | false |
```\nclass Solution:\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n if root == None: return 0\n if root.val > R: return self.rangeSumBST(root.left,L,R)\n if root.val < L: return self.rangeSumBST(root.right,L,R)\n return root.val + self.rangeSumBST(root.left,L,R) + self.rangeSumBST(root.right,L,R) \n \n```\n
| 89 | 1 |
['Python', 'Python3']
| 10 |
range-sum-of-bst
|
✅Beats 100% - Depth First Search - Explained with [ Video ] - C++/Java/Python/JS
|
beats-100-depth-first-search-explained-w-cp65
|
\n\n# YouTube Video Explanation:\n\n **If you want a video for this question please write in the comments** \n\n https://www.youtube.com/watch?v=ujU-jeO1v-k \n\
|
lancertech6
|
NORMAL
|
2024-01-08T01:56:09.773362+00:00
|
2024-01-08T02:55:05.075131+00:00
| 11,008 | false |
\n\n# YouTube Video Explanation:\n\n<!-- **If you want a video for this question please write in the comments** -->\n\n<!-- https://www.youtube.com/watch?v=ujU-jeO1v-k -->\n\nhttps://youtu.be/FxQ9OlcXFdc\n\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: https://www.youtube.com/@leetlogics/?sub_confirmation=1\n\n*Subscribe Goal: 1400 Subscribers*\n*Current Subscribers: 1300*\n\n---\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind the solution approach is to perform a depth-first traversal of the BST while leveraging the BST property to avoid unnecessary traversal. The steps of the approach are:\n\n1. If the current node is null (we\'ve reached a leaf\'s child), we can stop traversing this path.\n2. If the current node\'s value falls within `[low, high]`, we add it to the sum and continue to search both the left and right subtrees as there may be more nodes within the range.\n3. If the current node\'s value is less than `low`, we only need to traverse the right subtree because all values in the left subtree will also be less than `low`.\n4. If the current node\'s value is greater than `high`, we only need to traverse the left subtree, as all values in the right subtree will be greater than `high`.\n\nUsing these rules, the search efficiently skips parts of the tree that don\'t contribute to the range sum, which optimizes our algorithm significantly compared to a naive approach that checks every node.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe implementation of the solution involves the use of a recursive helper function called search, nested within the main function `rangeSumBST`. This is a common design pattern in recursive solutions, allowing the use of helper functions with additional parameters without changing the main function\'s signature. The algorithm uses this recursive function to perform a modified in-order traversal of the binary search tree. Here\'s a breakdown of how the algorithm works, with references to the data structures and patterns used:\n\n1. **Initialization**: A variable `self.ans` is initialized to 0. This will accumulate the sum of the node values that are within the range `[low, high]`.\n\n2. **Recursive Function (search)**: A nested function `search` is defined, which takes the current node as its parameter. The use of recursion is key here, enabling the function to traverse the tree depth-first.\n\n3. **Base Case**: At the beginning of the `search` function, there is a check to see if the current node is `None`. If it is, the function returns immediately. This check acts as the base case of the recursion, terminating the traversal at leaf nodes.\n\n4. **Range Check**:\n - If the current node\'s value is within the range `[low, high]` (inclusive), the value is added to `self.ans`. As this node is within the range, there might be other nodes within the range both to the left and right, so the function recursively calls itself on both `node.left` and `node.right`.\n5. **BST Property Util5ization**:\n\n - If the current node\'s value is less than `low`, the function calls itself recursively on `node.right` as all left child nodes of the current node are guaranteed to be out of the range.\n - If the current node\'s value is greater than `high`, the function calls itself recursively on `node.left` as all right child nodes of the current node are guaranteed to be out of the range.\n\n6. **Starting the Traversal**: The recursive `search` function is first called on the root node to start the depth-first traversal.\n\n7. **Returning the Answer**: Finally, after the recursive calls have completed, `self.ans` contains the sum of the values within the range, and this value is returned by the `rangeSumBST` function.\n\n# Complexity\n- Time complexity: The time complexity of the function is `O(N)`, where N is the number of nodes in the binary search tree. This is because, in the worst-case scenario, the function may have to visit every node in the tree.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: The space complexity of the recursion is `O(H)`, where H is the height of the tree. This complexity arises from the call stack that holds the recursive calls during the search process.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```Python []\n# Python3 Solution\nclass Solution:\n def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:\n def dfs(node):\n if not node:\n return\n if low <= node.val <= high:\n self.total_sum += node.val\n dfs(node.left)\n dfs(node.right)\n elif node.val < low:\n dfs(node.right)\n elif node.val > high:\n dfs(node.left)\n\n self.total_sum = 0\n dfs(root)\n return self.total_sum\n```\n```java []\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int rangeSumBST(TreeNode root, int low, int high) {\n if (root == null) {\n return 0;\n }\n \n if (low <= root.val && root.val <= high) {\n return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high);\n } \n else if (root.val < low) {\n return rangeSumBST(root.right, low, high);\n } \n else {\n return rangeSumBST(root.left, low, high);\n }\n }\n}\n```\n```C++ []\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int low, int high) {\n if (root == nullptr) {\n return 0;\n }\n\n if (low <= root->val && root->val <= high) {\n return root->val + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high);\n } else if (root->val < low) {\n return rangeSumBST(root->right, low, high);\n } else {\n return rangeSumBST(root->left, low, high);\n }\n }\n};\n```\n```JavaScript []\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} low\n * @param {number} high\n * @return {number}\n */\nvar rangeSumBST = function(root, low, high) {\n if (root === null) {\n return 0;\n }\n\n if (low <= root.val && root.val <= high) {\n return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high);\n } else if (root.val < low) {\n return rangeSumBST(root.right, low, high);\n } else {\n return rangeSumBST(root.left, low, high);\n }\n};\n\n```\n\n
| 75 | 5 |
['Tree', 'Depth-First Search', 'Binary Search Tree', 'Binary Tree', 'C++', 'Java', 'Python3', 'JavaScript']
| 11 |
range-sum-of-bst
|
0ms java solution faster than 100%
|
0ms-java-solution-faster-than-100-by-kin-8qqv
|
java\nclass Solution {\n public int rangeSumBST(TreeNode root, int low, int high) {\n if (root == null) return 0;\n int sum = 0;\n if (r
|
kingsleyadio
|
NORMAL
|
2021-03-25T23:51:46.850682+00:00
|
2021-03-25T23:51:46.850712+00:00
| 4,764 | false |
```java\nclass Solution {\n public int rangeSumBST(TreeNode root, int low, int high) {\n if (root == null) return 0;\n int sum = 0;\n if (root.val >= low && root.val <= high) sum += root.val;\n if (root.val > low) sum += rangeSumBST(root.left, low, high);\n if (root.val < high) sum += rangeSumBST(root.right, low, high);\n\n return sum;\n }\n}\n```
| 49 | 1 |
['Depth-First Search', 'Binary Search Tree', 'Recursion', 'Java']
| 5 |
range-sum-of-bst
|
Javascript solution
|
javascript-solution-by-mmartire-fqui
|
```\nvar rangeSumBST = function(root, L, R) {\n var sum = 0;\n if (root == null) {\n return sum;\n }\n\n if (root.val > L) {\n sum +=
|
mmartire
|
NORMAL
|
2019-09-04T00:40:01.978498+00:00
|
2019-09-04T00:40:01.978537+00:00
| 4,297 | false |
```\nvar rangeSumBST = function(root, L, R) {\n var sum = 0;\n if (root == null) {\n return sum;\n }\n\n if (root.val > L) {\n sum += rangeSumBST(root.left, L, R);\n }\n if (root.val <= R && root.val >= L) {\n sum += root.val;\n }\n if (root.val < R) {\n sum += rangeSumBST(root.right, L, R); \n } \n \n return sum;\n};
| 43 | 0 |
['JavaScript']
| 7 |
range-sum-of-bst
|
✅☑Beats 97.27% Users || [C++/Java/Python/JavaScript] || EXPLAINED🔥
|
beats-9727-users-cjavapythonjavascript-e-jw0p
|
PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n\n---\n# Approaches\n(Also explained in the code)\n\n1. Function Purpose: The function rangeSumBST calculates the sum of
|
MarkSPhilip31
|
NORMAL
|
2024-01-08T00:09:46.039231+00:00
|
2024-01-08T00:34:31.579624+00:00
| 4,250 | false |
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n\n---\n# Approaches\n(Also explained in the code)\n\n1. **Function Purpose:** The function `rangeSumBST` calculates the sum of node values within the given range `[L, R]` in a Binary Search Tree.\n\n1. **Base Case Handling:** If the current node (`root`) is `nullptr` (i.e., the tree/subtree is empty), the function returns `0` as there are no values to sum within an empty tree.\n\n1. **Node Value Comparison:** It checks whether the value of the current node `(root->val)` is within the given range `[L, R]`.\n\n1. **Recursive Sum Calculation:**\n\n - If the value falls within the range, it includes the current node\'s value in the sum and recursively calls the function for its left and right subtrees.\n - If the value is less than `L`, it means the current node\'s value and its left subtree\'s values are smaller than `L`, so it focuses only on the right subtree.\n - If the value is greater than `R`, it means the current node\'s value and its right subtree\'s values are greater than `R`, so it focuses only on the left subtree.\n1. **Returning Sum:** The function recursively computes the sum of values satisfying the given range conditions and returns the total sum of node values within the range `[L, R]`.\n\n\n# Complexity\n- Time complexity:\n $$O(n)$$\n \n\n- Space complexity:\n $$O(h)$$\n(*where H is the height of the tree*)\n \n\n\n# Code\n```C++ []\n\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int L, int R) {\n if (root == nullptr) {\n return 0;\n }\n \n if (root->val >= L && root->val <= R) {\n return root->val + rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R);\n } else if (root->val < L) {\n return rangeSumBST(root->right, L, R);\n } else {\n return rangeSumBST(root->left, L, R);\n }\n }\n}; \n\n\n\n```\n```Java []\nclass Solution {\n public int rangeSumBST(TreeNode root, int L, int R) {\n if (root == null) {\n return 0;\n }\n \n if (root.val >= L && root.val <= R) {\n return root.val + rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R);\n } else if (root.val < L) {\n return rangeSumBST(root.right, L, R);\n } else {\n return rangeSumBST(root.left, L, R);\n }\n }\n}\n\n\n\n```\n```python3 []\nclass Solution:\n def rangeSumBST(self, root, L, R):\n if not root:\n return 0\n \n if L <= root.val <= R:\n return root.val + self.rangeSumBST(root.left, L, R) + self.rangeSumBST(root.right, L, R)\n elif root.val < L:\n return self.rangeSumBST(root.right, L, R)\n else:\n return self.rangeSumBST(root.left, L, R)\n\n\n\n```\n```javascript []\nvar rangeSumBST = function(root, L, R) {\n if (!root) {\n return 0;\n }\n \n if (root.val >= L && root.val <= R) {\n return root.val + rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R);\n } else if (root.val < L) {\n return rangeSumBST(root.right, L, R);\n } else {\n return rangeSumBST(root.left, L, R);\n }\n};\n\n\n\n```\n---\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
| 33 | 5 |
['Tree', 'Depth-First Search', 'Binary Search Tree', 'Binary Tree', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']
| 9 |
range-sum-of-bst
|
~100.00% fast in memory and run-time dfs - recursive/iterative solution
|
10000-fast-in-memory-and-run-time-dfs-re-uq2b
|
Compare yourself, as the different ways are below: satisfied? \nDon\'t look at runtime, as this may change time to time on each submission. Have a look at optim
|
alokgupta
|
NORMAL
|
2020-02-03T09:36:06.563503+00:00
|
2020-02-03T09:36:06.563556+00:00
| 5,478 | false |
Compare yourself, as the different ways are below: satisfied? \nDon\'t look at runtime, as this may change time to time on each submission. Have a look at optimized approach.\n\n-------\nRuntime: 84 ms, faster than 98.75% of C++ online submissions for Range Sum of BST.\nMemory Usage: 41.1 MB, less than 99.09% of C++ online submissions for Range Sum of BST.\nIf root\'s value is greater than L then move left, and if it\'s value if less than R then move right.\nTime Complexity: **O(N)**, where N is the number of nodes in the tree.\nSpace Complexity: **O(H)**, where H is the height of the tree. i.e. **O(1)**\n```\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int L, int R) {\n int rangeSum(0);\n stack<TreeNode*> st;\n st.push(root);\n while(!st.empty()){\n TreeNode* node = st.top(); st.pop();\n if(node->val>=L && node->val<=R) rangeSum+=node->val;\n if(node->val > L) {if(node->left) st.push(node->left);}\n if(node->val < R) {if(node->right) st.push(node->right);}\n }\n return rangeSum;\n }\n};\n```\n\n---------------\nTime Complexity **O(n)** & Space Complexity **O(n)**\nRuntime: 96 ms, faster than 95.88% of C++ online submissions for Range Sum of BST.\nMemory Usage: 41.1 MB, less than 100.00% of C++ online submissions for Range Sum of BST.\n```\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int L, int R) {\n if(!root) return 0;\n return ((root->val>=L && root->val<=R)? root->val : 0) + rangeSumBST(root->left,L,R) + rangeSumBST(root->right,L,R);\n }\n};\n```\n\n---------------\nRuntime: 80 ms, faster than 92.88% of C++ online submissions for Range Sum of BST.\nMemory Usage: 41.2 MB, less than 100.00% of C++ online submissions for Range Sum of BST.\n\n```\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int L, int R) {\n if(!root) return 0;\n return ((root->val>=L && root->val<=R)? (root->val + rangeSumBST(root->left,L,R) + rangeSumBST(root->right,L,R)) : (root->val<L)? rangeSumBST(root->right,L,R): rangeSumBST(root->left,L,R));\n }\n};\n```\n\n--------------\nRuntime: 92 ms, faster than 96.85% of C++ online submissions for Range Sum of BST.\nMemory Usage: 41.2 MB, less than 89.09% of C++ online submissions for Range Sum of BST.\n```\nclass Solution {\npublic:\n int helper(TreeNode* root, int L, int R, int rangeSum){\n if(!root) return 0;\n else if(root->val>=L && root->val<=R){\n rangeSum+=helper(root->left,L,R,0);\n rangeSum+=helper(root->right,L,R,0);\n return rangeSum + root->val;\n }else if(root->val > L){\n rangeSum+=helper(root->left,L,R,0);\n return rangeSum;\n }else if(root->val < R){\n rangeSum+=helper(root->right,L,R,0);\n return rangeSum;\n }\n return 0;\n }\n int rangeSumBST(TreeNode* root, int L, int R) {\n std::ios::sync_with_stdio(false);\n return helper(root,L,R,0);\n }\n};\n```\n\n-----------------\nRuntime: 92 ms, faster than 96.92% of C++ online submissions for Range Sum of BST.\nMemory Usage: 41.2 MB, less than 86.36% of C++ online submissions for Range Sum of BST.\nSolution: **We traverse the tree using a depth first search. If node.val falls outside the range [L, R], (for example node.val < L), then we know that only the right branch could have nodes with value inside [L, R].**\nTC: **O(n)**, SC: **O(n)**\n```\nclass Solution { // dfs\nprivate:\n int rangeSum;\npublic:\n void dfs(TreeNode* root, int L, int R){\n if(!root) return;\n if(root->val>=L && root->val<=R) rangeSum+=root->val;\n if(root->val > L) dfs(root->left,L,R);\n if(root->val < R) dfs(root->right,L,R);\n }\n int rangeSumBST(TreeNode* root, int L, int R) {\n rangeSum = 0;\n dfs(root,L,R);\n return rangeSum;\n }\n};\n```\n\n----------------------\nRuntime: 148 ms, faster than 76.44% of C++ online submissions for Range Sum of BST.\nMemory Usage: 41.2 MB, less than 88.18% of C++ online submissions for Range Sum of BST.\n\n```\nclass Solution {\npublic:\n void dfs(TreeNode* root, int &rangeSum, int L, int R, bool isDone){\n if(!root || isDone) return;\n dfs(root->left,rangeSum,L,R,false);\n if(root->val>=L && root->val<=R){\n rangeSum+=root->val;\n if(root->val==R) isDone = true;\n }\n dfs(root->right,rangeSum,L,R,false);\n }\n int rangeSumBST(TreeNode* root, int L, int R) {\n int rangeSum(0);\n dfs(root,rangeSum,L,R,false);\n return rangeSum;\n }\n};\n```\n\n--------\n\n
| 29 | 0 |
['Depth-First Search', 'Recursion', 'C', 'Iterator', 'C++']
| 3 |
range-sum-of-bst
|
cpp beats 96%, better than O(n) traversal.
|
cpp-beats-96-better-than-on-traversal-by-zb2g
|
\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : v
|
LightSpeedSonic
|
NORMAL
|
2019-03-09T05:37:21.455055+00:00
|
2019-03-09T05:37:21.455114+00:00
| 5,886 | false |
```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int L, int R) {\n \n if(!root) return 0;\n \n if(root->val >= L && root->val <= R){\n return root->val + rangeSumBST(root->left,L,R) + rangeSumBST(root->right,L,R);\n }else if(root->val < L){\n return rangeSumBST(root->right,L,R);\n }else {\n return rangeSumBST(root->left,L,R);\n }\n }\n \n \n};\n```
| 29 | 4 |
[]
| 10 |
range-sum-of-bst
|
C++ 2 lines
|
c-2-lines-by-votrubac-968q
|
Just doing regular tree traversal and adding values within [L, R]. Note that in the solution description, we are given BST, however, this solution works for an
|
votrubac
|
NORMAL
|
2018-11-11T04:02:08.750904+00:00
|
2018-11-11T04:02:08.750953+00:00
| 4,840 | false |
Just doing regular tree traversal and adding values within [L, R]. Note that in the solution description, we are given BST, however, this solution works for any binary tree.\n\nOf course, we can optimize a bit for the fact that this is BST. I checked the runtime and did not see any difference in the runtime. Both naive and optimized solution gave me 68 ms.\n```\nint rangeSumBST(TreeNode* root, int L, int R) {\n if (root == nullptr) return 0;\n return (root->val >= L && root->val <= R ? root->val : 0) +\n rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R);\n}\n```
| 29 | 3 |
[]
| 3 |
range-sum-of-bst
|
🔥Python3🔥 DFS (One-liner || Recursive || Iterative Explained)
|
python3-dfs-one-liner-recursive-iterativ-l3xe
|
One-liner\npython\nclass Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n return 0 if not root else self.ran
|
MeidaChen
|
NORMAL
|
2022-12-07T00:26:22.304240+00:00
|
2024-01-04T19:25:30.236356+00:00
| 1,987 | false |
**One-liner**\n```python\nclass Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n return 0 if not root else self.rangeSumBST(root.right,low,high) + self.rangeSumBST(root.left,low,high) + int(low<=root.val<=high) * root.val\n```\n\n**Recursive 1** (more readable)\n```python\nclass Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n \n if not root: \n return 0\n \n # When value is less than low, everything on it\'s left doesn\'t matter, \n # so only return the sum from its right children\n if root.val<low: \n return self.rangeSumBST(root.right,low,high)\n \n # Same thing for high.\n elif root.val>high: \n return self.rangeSumBST(root.left,low,high)\n \n # The current value is in the range, so return the sum of its left, right and own value\n else:\n return root.val + self.rangeSumBST(root.right,low,high) + self.rangeSumBST(root.left,low,high)\n```\n\n**Recursive 2**\n```python\nclass Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n res = 0\n def dfs(node):\n nonlocal res\n if not node: return\n \n # increase res only when the node value is in the range\n if low<=node.val<=high: res += node.val\n \n # The only time we don\'t want to go left, is when the nodel value <= low.\n # Because it is a BST, and if the current value is aleady <= low, \n # there is no more hope!\n if node.val>low: dfs(node.left)\n \n # Same as above, but going right\n if node.val<high: dfs(node.right)\n\n dfs(root)\n return res\n```\n\n**Iterative** (same idea as Recursive 2)\n```python\nclass Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n res = 0\n q = [root]\n while q:\n cur = q.pop()\n if cur:\n if low <= cur.val <= high:\n res += cur.val\n if cur.val > low:\n q.append(cur.left)\n if cur.val < high:\n q.append(cur.right)\n return res\n```\n\n**Upvote** if you like this post.\n\n**Connect with me on [LinkedIn](https://www.linkedin.com/in/meida-chen-938a265b/)** if you\'d like to discuss other related topics\n\n\uD83C\uDF1F If you are interested in **Machine Learning** || **Deep Learning** || **Computer Vision** || **Computer Graphics** related projects and topics, check out my **[YouTube Channel](https://www.youtube.com/@meidachen8489)**! Subscribe for regular updates and be part of our growing community.
| 28 | 1 |
['Python']
| 1 |
range-sum-of-bst
|
C++ EASY TO SOLVE || Detailed Explanation While Optimizing Approach
|
c-easy-to-solve-detailed-explanation-whi-e8dq
|
Intuition:\nActually the question is pretty straightforward ,Basically the question maker is asking us to add all the numbers in a BST with a certain range giv
|
Cosmic_Phantom
|
NORMAL
|
2021-12-14T02:43:57.738080+00:00
|
2024-08-23T02:42:34.130645+00:00
| 4,927 | false |
**Intuition:**\nActually the question is pretty straightforward ,Basically the question maker is asking us to add all the numbers in a BST with a certain range given for numbers like say range is given as [Low,High]=[2,7] then we need to add all the values in BST with the numbers satisfying this range. So major people who thought of a solution will be either using recursion ,DFS or BFS.\n*Now, let\'s talk about approach*\n\n**Algorithm:**\nIn the following algorithm we will be discussing the solution of dfs approach .\n1. let` sumofRange` be a variable that will be our final result . After this let\'s declare a dfs helper function .\n2. The base case will be when the tree is empty so we return null\n3. we have to find the` sumofRange` so for that we need to add all the root values which satisfyes the condition that `node values should be more than low and less than high` .If this is true than add it to `sumofRange`\n4. After this let\'s dig the depth\'s of the tree i.e Left childs and Right childs.\n5. Now just call out the dfs helper function in the main function \n\n**Code:-**\n```\nclass Solution {\npublic: \n void dfs(TreeNode* root, int L, int R, int& sumOfRange){\n if(!root) return;\n if(root->val >= L && root->val <= R) sumOfRange += root->val;\n if(root->val > L) dfs(root->left, L, R, sumOfRange);\n if(root->val < R) dfs(root->right, L, R, sumOfRange);\n }\n \n int rangeSumBST(TreeNode* root, int low, int high) {\n int sumOfRange = 0;\n dfs(root, low, high, sumOfRange);\n return sumOfRange;\n }\n};\n```\n**Time Complexity:** *`O(n) [n=number of nodes]`*\n**Space Complexity:** *`O(h) [h=height of tree] [Considering recursive calls]`*\n\n\n**Space Optimized Approach:**\nAfter exploring some other options, I found that we can actually optimize the space.\nThe logic is almost same as we discussed in the above approach .The main difference is that we use a stack for storing the data of nodes . So everytime we can just peek and pop the last values that we entered\n\n```\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int L, int R) {\n int sumofRange(0);\n stack<TreeNode*> stack;\n stack.push(root);\n while(!stack.empty()){\n TreeNode* node = stack.top(); stack.pop();\n if(node->val>=L && node->val<=R) sumofRange+=node->val;\n if(node->val > L) {if(node->left) stack.push(node->left);}\n if(node->val < R) {if(node->right) stack.push(node->right);}\n }\n return sumofRange;\n }\n};\n```\n\n**Time Complexity:** *`O(n) [n=number of nodes]`*\n**Space Complexity:** *`O(h) [h=height of the tree]`*\n
| 25 | 0 |
['Depth-First Search', 'Recursion', 'C', 'Binary Tree', 'C++']
| 5 |
range-sum-of-bst
|
JavaScript 2 solutions, easy to understand, beats 100%
|
javascript-2-solutions-easy-to-understan-e4fl
|
Sum while recursing through the tree\n\nvar rangeSumBST = function(root, L, R) {\n // base case\n if(root == null) {\n return 0;\n }\n \n
|
becs
|
NORMAL
|
2018-11-14T23:56:39.530746+00:00
|
2018-11-14T23:56:39.530791+00:00
| 2,037 | false |
1. Sum while recursing through the tree\n```\nvar rangeSumBST = function(root, L, R) {\n // base case\n if(root == null) {\n return 0;\n }\n \n if(root.val > R) {\n return rangeSumBST(root.left, L, R);\n } else if(root.val < L) {\n return rangeSumBST(root.right, L, R);\n } else {\n return root.val + rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R);\n }\n};\n```\n\n2. Do inorder traversal to get all nodes on tree in order, and then sum all values >= L and <=R. This is less efficient than previous solution because we are traversing all nodes, but this can be easier to understand.\n```\nvar rangeSumBST = function(root, L, R) {\n var arr = [], sum=0;\n inorder(root, arr);\n \n for(var i=0; i<arr.length; i++) {\n if(arr[i] >= L && arr[i] <= R) {\n sum = sum + arr[i];\n }\n }\n \n return sum;\n};\n\nvar inorder = function(root, arr) {\n if(root == null) {\n return;\n }\n \n inorder(root.left, arr);\n arr.push(root.val);\n inorder(root.right, arr);\n \n return;\n}\n```
| 21 | 1 |
[]
| 1 |
range-sum-of-bst
|
python use visualization help you think about it.
|
python-use-visualization-help-you-think-2nxa6
|
L = 7, R = 15, sum=32:\n\n *10\n / \\\n *5 *15\n / \\ \\\n 3 *7 18\n\n\t \n2. L = 6, R = 10, sum=23 :\n\n\t
|
jsleetw
|
NORMAL
|
2019-08-03T08:20:41.538020+00:00
|
2019-08-03T08:22:56.480402+00:00
| 2,882 | false |
1. L = 7, R = 15, sum=32:\n```\n *10\n / \\\n *5 *15\n / \\ \\\n 3 *7 18\n```\n\t \n2. L = 6, R = 10, sum=23 :\n```\n\t *10\n / \\\n 5 15\n / \\ / \\\n 3 *7 13 18\n / /\n 1 *6\n\n```\n```\nclass Solution(object):\n def rangeSumBST(self, root, L, R):\n def dfs(node):\n if node:\n if L<= node.val <= R:\n self.ans += node.val\n #print(node.val)\n if node.val>L:\n dfs(node.left)\n if node.val<R:\n dfs(node.right)\n self.ans = 0\n dfs(root)\n return self.ans\n\n
| 20 | 0 |
['Depth-First Search', 'Python']
| 4 |
range-sum-of-bst
|
Python3 | Easy to understand | InOrder Traversal
|
python3-easy-to-understand-inorder-trave-vnht
|
\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.righ
|
geom1try
|
NORMAL
|
2018-11-13T22:11:50.139237+00:00
|
2019-09-06T22:19:12.108103+00:00
| 7,001 | false |
```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def rangeSumBST(self, root, L, R):\n """\n :type root: TreeNode\n :type L: int\n :type R: int\n :rtype: int\n """\n return self.inorder(root, 0, L, R)\n \n def inorder(self, root, value, L, R):\n if root:\n value = self.inorder(root.left, value, L, R)\n if root.val >= L and root.val <= R:\n value += root.val\n value = self.inorder(root.right, value, L, R)\n \n return value\n```\n\n**UPDATE**\nWe may optimize this by setting the \n```\nif root.val >= L and root.val <= R:\n``` \nas\n```\nif root.val > R:\n\treturn value\nelif root.val >= L:\n\tvalue += root.val\n```
| 19 | 0 |
[]
| 4 |
range-sum-of-bst
|
Python 1-liner
|
python-1-liner-by-cenkay-9n3u
|
\nclass Solution:\n def rangeSumBST(self, root, L, R):\n return root and self.rangeSumBST(root.left, L, R) + self.rangeSumBST(root.right, L, R) + (L <
|
cenkay
|
NORMAL
|
2018-11-11T06:38:44.362461+00:00
|
2018-11-11T06:38:44.362504+00:00
| 4,035 | false |
```\nclass Solution:\n def rangeSumBST(self, root, L, R):\n return root and self.rangeSumBST(root.left, L, R) + self.rangeSumBST(root.right, L, R) + (L <= root.val <= R) * root.val or 0\n```\n* More readable\n```\nclass Solution:\n def rangeSumBST(self, root, L, R):\n if not root: return 0\n l = self.rangeSumBST(root.left, L, R)\n r = self.rangeSumBST(root.right, L, R)\n return l + r + (L <= root.val <= R) * root.val\n```
| 18 | 4 |
[]
| 4 |
range-sum-of-bst
|
Beats 99.98% Users - C++, JAVA, Python, JavaScript || With explanation ||
|
beats-9998-users-c-java-python-javascrip-x3n1
|
\n---\n\n\n\n---\n\n\n# Approach\n Describe your approach to solving the problem. \n\n1. Iterative In-Order Traversal:\n - The code uses a modified in-order tr
|
Vivekkrsk
|
NORMAL
|
2024-01-08T02:05:48.081999+00:00
|
2024-01-08T02:20:55.769624+00:00
| 2,940 | false |
\n---\n\n\n\n---\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n**1. Iterative In-Order Traversal:**\n - The code uses a modified in-order traversal to visit nodes in ascending order without using recursion.\n - It achieves this by temporarily linking rightmost nodes of left subtrees to their parents, creating a kind of threaded binary tree.\n\n**2. Range Check and Sum Addition:**\n - For each visited node, its value is checked against the `low` and `high` range:\n - If it falls within the range, its value is added to the `sum` variable.\n\n**3. Right Subtree Exploration:**\n - After processing a node, the traversal continues to its right subtree to explore values that might also fall within the range.\n\n**4. Temporary Link Removal:**\n - The temporary links created during the traversal are removed to restore the original tree structure.\n\n**5. Final Sum:**\n - The function returns the `sum` variable, which holds the accumulated value of all nodes within the specified range.\n\n**Time Complexity:**\n - O(N)\n - The traversal visits each node in the BST exactly once, leading to linear time complexity.\n\n**Space Complexity:**\n - O(1)\n - The space used for variables remains constant, independent of the BST size.\n - The temporary link manipulation doesn\'t require additional space in terms of asymptotic complexity.\n\n\n# Code\n```C++ []\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\n\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int low, int high) {\n int sum=0;\n while(root){\n if(root->left){\n TreeNode* temp=root->left;\n TreeNode* curr=root->left;\n while(temp->right){\n temp=temp->right;\n }\n temp->right=root;\n root->left=NULL;\n root=curr;\n }\n else{\n if(root->val>=low&&root->val<=high){\n sum+=root->val;\n }\n root=root->right;\n }\n }\n return sum;\n }\n};\n```\n```java []\nclass Solution {\n public int rangeSumBST(TreeNode root, int low, int high) {\n int sum = 0;\n while (root != null) {\n if (root.left != null) {\n TreeNode temp = root.left;\n while (temp.right != null && temp.right != root) {\n temp = temp.right;\n }\n if (temp.right == null) {\n temp.right = root;\n root = root.left;\n } else {\n temp.right = null;\n }\n } else {\n if (root.val >= low && root.val <= high) {\n sum += root.val;\n }\n root = root.right;\n }\n }\n return sum;\n }\n}\n\n```\n```python []\nclass Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n sum = 0\n node = root\n while node:\n if node.left:\n prev = node.left\n while prev.right and prev.right != node:\n prev = prev.right\n if not prev.right:\n prev.right = node\n node = node.left\n else:\n prev.right = None\n elif low <= node.val <= high:\n sum += node.val\n node = node.right\n return sum\n\n```\n```javascript []\nclass Solution {\n rangeSumBST(root, low, high) {\n let sum = 0;\n let node = root;\n while (node) {\n if (node.left) {\n let prev = node.left;\n while (prev.right && prev.right !== node) {\n prev = prev.right;\n }\n if (!prev.right) {\n prev.right = node;\n node = node.left;\n } else {\n prev.right = null;\n }\n } else {\n if (low <= node.val && node.val <= high) {\n sum += node.val;\n }\n node = node.right;\n }\n }\n return sum;\n }\n}\n\n```\n\n
| 17 | 0 |
['Binary Search Tree', 'Binary Tree', 'Python', 'C++', 'Java', 'JavaScript']
| 7 |
range-sum-of-bst
|
Intuitive JavaScript Solution
|
intuitive-javascript-solution-by-dawchih-zmb0
|
\n/**\n * @param {TreeNode} root\n * @param {number} L\n * @param {number} R\n * @return {number}\n */\nvar rangeSumBST = function(root, L, R) {\n // check i
|
dawchihliou
|
NORMAL
|
2019-06-26T06:57:21.744714+00:00
|
2019-06-26T06:57:21.744751+00:00
| 3,128 | false |
```\n/**\n * @param {TreeNode} root\n * @param {number} L\n * @param {number} R\n * @return {number}\n */\nvar rangeSumBST = function(root, L, R) {\n // check if value is in the given range\n const isInBetween = val => val >= L && val <= R;\n // sum the value if it\'s in the range\n const add = (val, sum) => isInBetween(val) ? sum += val : sum;\n\t// traverse through the nodes and sum the values in range\n const preorder =(root, sum) => {\n if (!root) return sum;\n return add(root.val, sum) + preorder(root.left, sum) + preorder(root.right, sum);\n } \n return preorder(root, 0)\n};\n```
| 17 | 0 |
['Recursion', 'JavaScript']
| 3 |
range-sum-of-bst
|
C++/Python binary search Tree|69 ms Beats 99.46%
|
cpython-binary-search-tree69-ms-beats-99-vedy
|
Intuition\n Describe your first thoughts on how to solve this problem. \nUse preOrder to solve.\n2nd approach uses postOrder.\n3rd approach uses inOrder, note t
|
anwendeng
|
NORMAL
|
2024-01-08T01:14:36.893812+00:00
|
2024-01-08T09:05:22.079826+00:00
| 2,339 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse preOrder to solve.\n2nd approach uses postOrder.\n3rd approach uses inOrder, note that inOrder traversal is a way of sorting.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis is a binary Search Tree problem. If you understand how to build the binary search tree, you can solve it.\n\n[Please turn on English subtitles if necessary]\n[https://youtu.be/KHVXYo7LxZE?si=2AU_RCL8SHq5WR0R](https://youtu.be/KHVXYo7LxZE?si=2AU_RCL8SHq5WR0R)\n\nAll testcases are expressed in their array representations.\nThe value for root is always on the head.\nInsert a node with value x in this BST, how to do it?\n- Loop: check whether `x>node->val`\nif yes, the node with value x must be in right subtree; let\n`node=node->right` , if `!node` insert here.\notherwise this node is in the left subtree; let\n`node=node->left` , if `!node` insert here.\n\nUse preOrder traversal can do the job; other traversals, eq. postOrder, inOrder, can do also. `rangeSumBST` can be implemented in the similar way.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nsystem stack + $$O(1)$$\n# Code 83 ms Beats 95.10%\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\n #pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n int sum=0;\n void preOrder(TreeNode* root, int low, int high){\n if (!root) return ;\n if (root->val<=high && root->val>=low) \n sum+=root->val;\n preOrder(root->left, low, high);\n preOrder(root->right, low, high);\n }\n int rangeSumBST(TreeNode* root, int low, int high) {\n preOrder(root, low, high);\n return sum; \n }\n};\n\n```\n# Python Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n ans=0\n def preOrder(root, low, high):\n nonlocal ans\n if not root: return\n if low<=root.val<=high:\n ans+=root.val\n preOrder(root.left, low, high)\n preOrder(root.right, low, high)\n \n preOrder(root, low, high)\n return ans\n \n```\n# C++ using postOrder||75 ms Beats 98.41%\n```\n int sum=0;\n void postOrder(TreeNode* root, int low, int high){\n if (!root) return ;\n postOrder(root->left, low, high);\n postOrder(root->right, low, high);\n if (root->val<=high && root->val>=low) \n sum+=root->val;\n }\n int rangeSumBST(TreeNode* root, int low, int high) {\n postOrder(root, low, high);\n return sum; \n }\n```\n# C++ using Inorder||69 ms Beats 99.46%\n```\n int sum=0;\n void inOrder(TreeNode* root, int low, int high){\n if (!root) return ;\n int x=move(root->val);\n if (x>high) inOrder(root->left, low, high);\n else if (x<=high && x>=low){ \n inOrder(root->left, low, high);\n sum+=x;\n inOrder(root->right, low, high);\n }\n else inOrder(root->right, low, high);\n }\n int rangeSumBST(TreeNode* root, int low, int high) {\n inOrder(root, low, high);\n return sum; \n }\n```
| 15 | 0 |
['Binary Search Tree', 'C++', 'Python3']
| 7 |
range-sum-of-bst
|
Python 3 || 6 lines, two versions, w/ explanation || T/S: 93% / 94%
|
python-3-6-lines-two-versions-w-explanat-37c0
|
A binary search tree is more than just a binary tree. For each node node, every node value in node\'s left tree is less than node.val, and every node value in n
|
Spaulding_
|
NORMAL
|
2022-12-07T00:48:52.253889+00:00
|
2024-05-31T18:20:13.537783+00:00
| 817 | false |
A binary *search* tree is more than just a binary tree. For each node `node`, every node value in `node`\'s left tree is less than `node.val`, and every node value in `node`\'s right tree is greater than `node.val`.\n\nHere\'s the plan:\n- Traverse the tree recursively or iteratively, and at each node visited, return the sum of all qualifying node values in its two subtrees. However, for any `node`:\n\n- If `node.val` is less than `low`, then we know that each value in node\'s left subtree is also less than `low`; if so, we do not need to traverse *node*\'s left subtree.\n- Likewise, If `node.val` is greater than `high`, then we know that each value in `node`\'s right subtree is also greater than `high`; if so, we do not need to traverse `node`\'s right subtree.\n\nHere is a recursive version:\n\n```\nclass Solution: \n def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:\n\n def dfs(node):\n\n if not node: return 0\n\n if node.val < low: return dfs(node.right)\n if node.val > high: return dfs(node.left )\n \n return dfs(node.left ) + dfs(node.right) + node.val\n\n return dfs(root)\n```\n\n```\n```\n\nAnd here\'s a iterative version:\n\n```\nclass Solution: \n def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:\n\n ans, stack = 0, deque([root])\n\n while stack:\n node = stack.pop()\n if not node: continue\n\n if node.val < low: stack.append(node.right)\n elif node.val > high: stack.append(node.left )\n else:\n ans+= node.val\n stack.append(node.left )\n stack.append(node.right)\n \n return ans\n```\nhttps://leetcode.com/problems/range-sum-of-bst/submissions/1273539127/\n\nI could be wrong, but I think that, for each solution, time complexity is *O*(*N*) and space complexityis *O*(*H*), in which *N* ~ the number of nodes and *H* ~ the height of the tree.
| 15 | 1 |
['Python3']
| 3 |
range-sum-of-bst
|
✅ [Python/C++/Java] DFS & BFS & binary search (explained) + BONUS ONE-LINER
|
pythoncjava-dfs-bfs-binary-search-explai-l9f5
|
\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.\n*\nThis solution employs conditional traversal of a Binary Search Tree. Time complexity is linear: *O(N). Spac
|
stanislav-iablokov
|
NORMAL
|
2022-12-07T00:34:04.972016+00:00
|
2022-12-07T01:31:49.239978+00:00
| 502 | false |
**\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n****\nThis solution employs conditional traversal of a Binary Search Tree. Time complexity is linear: **O(N)**. Space complexity is logarithmic (for a balanced tree): **O(logN)**.\n****\n\n**Comment.** Binary Search Tree (BST) is a type of binary tree for which the left (right) subtree of each node is also a BST with all values being less (greater) than the node\'s value. This defines a recursive strategy to compute range sums, namely:\n1. Take node\'s value if it\'s in range. \n2. If node\'s value is greater than the lower bound then search for valid values in the left subtree.\n3. If node\'s value is less than the upper bound then search for valid values in the right subtree.\n\n**Python #1.** DFS.\n```\nclass Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n \n if not root : return 0\n \n s = root.val if low <= root.val <= high else 0\n if low <= root.val : s += self.rangeSumBST(root.left, low, high)\n if high >= root.val : s += self.rangeSumBST(root.right, low, high)\n \n return s\n```\n\n**Python #2.** BFS.\n```\nclass Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n dq, s = deque([root]), 0\n while dq:\n node = dq.popleft()\n if low <= node.val <= high : s += node.val\n if low <= node.val and node.left : dq.append(node.left)\n if high >= node.val and node.right : dq.append(node.right)\n return s\n```\n\nThere is also a more expensive, however, interesting approach. \n\n**Python #3.** Collect values in order then binary search.\n```\nclass Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n \n def inorder(n, v):\n if n: inorder(n.left, v), v.append(n.val), inorder(n.right, v)\n \n vals = []\n inorder(root, vals)\n \n return sum(vals[bisect_left(vals, low) : bisect_right(vals, high)])\n```\n\n<iframe src="https://leetcode.com/playground/2RVvrN38/shared" frameBorder="0" width="800" height="260"></iframe>\n\n**\u2705 YOU MADE IT TILL THE BONUS SECTION... YOUR GREAT EFFORT DESERVES UPVOTING THIS POST!**\n\n**Python.** DFS one-liner.\n```\nclass Solution:\n def rangeSumBST(self, r, l, h):\n \n return 0 if not r else (l <= r.val <= h) * r.val + \\\n self.rangeSumBST(r.right, l, h) + \\\n self.rangeSumBST(r.left, l, h)\n```
| 15 | 0 |
[]
| 3 |
range-sum-of-bst
|
[Python] 2 Elegant Solutions. Recursive and Iterative
|
python-2-elegant-solutions-recursive-and-kunp
|
\nclass Solution:\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n ## RC ##\n ## APPROACH : RECURSION ##\n\t\t## TIME COMPLEXI
|
101leetcode
|
NORMAL
|
2020-06-24T16:26:09.008653+00:00
|
2020-06-24T16:26:09.008690+00:00
| 2,200 | false |
```\nclass Solution:\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n ## RC ##\n ## APPROACH : RECURSION ##\n\t\t## TIME COMPLEXITY : O(N) ##\n\t\t## SPACE COMPLEXITY : O(H) ##\n \n def dfs(node):\n if not node: return 0\n if node.val < L: return dfs(node.right)\n elif node.val > R: return dfs(node.left)\n else: return dfs(node.left) + dfs(node.right) + node.val\n return dfs(root)\n \n ## APPROACH : ITERATIVE ##\n\t\t## TIME COMPLEXITY : O(N) ##\n\t\t## SPACE COMPLEXITY : O(H) ##\n stack = [root]\n ans = 0\n while(stack):\n node = stack.pop()\n if node:\n if L <= node.val <= R: ans += node.val\n if L < node.val: stack.append(node.left)\n if R > node.val: stack.append(node.right)\n return ans\n\n```
| 15 | 0 |
['Python', 'Python3']
| 1 |
range-sum-of-bst
|
Simple Recursive Solution. Faster than 96%
|
simple-recursive-solution-faster-than-96-7jnu
|
\nconst rangeSumBST = (root, L, R) => {\n let sum = 0;\n const traverse = (root) => {\n if (root.val >= L && root.val <= R) sum += root.val;\n
|
yashpandit
|
NORMAL
|
2020-01-14T19:54:13.258639+00:00
|
2020-01-14T19:54:13.258684+00:00
| 1,431 | false |
```\nconst rangeSumBST = (root, L, R) => {\n let sum = 0;\n const traverse = (root) => {\n if (root.val >= L && root.val <= R) sum += root.val;\n if (root.left !== null) traverse(root.left);\n if (root.right !== null) traverse(root.right);\n }\n traverse(root);\n return sum;\n};\n```
| 15 | 1 |
['Recursion', 'JavaScript']
| 3 |
range-sum-of-bst
|
C++ Recursion!
|
c-recursion-by-ddev-5rcr
|
int rangeSumBST(TreeNode* root, int L, int R) {\n if(!root || L > R)\n return 0;\n \n if(root->val < L)\n return rang
|
ddev
|
NORMAL
|
2018-11-11T04:00:59.096311+00:00
|
2018-11-11T04:00:59.096369+00:00
| 4,189 | false |
int rangeSumBST(TreeNode* root, int L, int R) {\n if(!root || L > R)\n return 0;\n \n if(root->val < L)\n return rangeSumBST(root->right, L, R);\n \n if(root->val > R)\n return rangeSumBST(root->left, L, R);\n \n return root->val + rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R);\n }
| 15 | 0 |
[]
| 3 |
range-sum-of-bst
|
Python 3 Faster than 99.54% Simple Solution
|
python-3-faster-than-9954-simple-solutio-u9ix
|
````\nclass Solution:\n def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:\n if root:\n if root.valhigh:\n r
|
anurag_tiwari
|
NORMAL
|
2021-05-17T04:52:36.307795+00:00
|
2021-05-17T04:52:36.307838+00:00
| 1,643 | false |
````\nclass Solution:\n def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:\n if root:\n if root.val<low:\n return self.rangeSumBST(root.right,low,high)\n elif root.val>high:\n return self.rangeSumBST(root.left,low,high)\n return root.val + self.rangeSumBST(root.left,low,high) + self.rangeSumBST(root.right,low,high)\n else:\n return 0
| 12 | 0 |
['Recursion', 'Python', 'Python3']
| 0 |
range-sum-of-bst
|
Simple, easy to understand, java 0 ms, faster than 100.00%, using dfs, clean code with comment
|
simple-easy-to-understand-java-0-ms-fast-7l77
|
\n\nclass Solution {\n int sum;\n public int rangeSumBST(TreeNode root, int low, int high) {\n sum = 0;\n \n dfs(root, low, high);\n
|
satyaDcoder
|
NORMAL
|
2021-03-07T06:24:12.506593+00:00
|
2021-03-07T06:25:06.197056+00:00
| 1,282 | false |
```\n\nclass Solution {\n int sum;\n public int rangeSumBST(TreeNode root, int low, int high) {\n sum = 0;\n \n dfs(root, low, high);\n \n return sum;\n }\n private void dfs(TreeNode node, int low, int high){\n if(node == null) return;\n \n int currentVal = node.val;\n \n //add in sum, if its value in range\n if(currentVal >= low && currentVal <= high) sum += currentVal;\n \n //no need to check in left, if current val is less than low\n //As it given,this is BST, so in left there will lesser number\n if(currentVal >= low)\n dfs(node.left, low, high);\n \n //no need to check in right, if current val is greater that high\n if(currentVal <= high)\n dfs(node.right, low, high);\n }\n \n}\n```
| 12 | 1 |
['Depth-First Search', 'Recursion', 'Java']
| 0 |
range-sum-of-bst
|
Java recursion
|
java-recursion-by-wangzi6147-xd40
|
\nclass Solution {\n public int rangeSumBST(TreeNode root, int L, int R) {\n if (root == null) {\n return 0;\n }\n if (root.v
|
wangzi6147
|
NORMAL
|
2018-11-11T04:02:12.922952+00:00
|
2018-11-11T04:02:12.923002+00:00
| 2,578 | false |
```\nclass Solution {\n public int rangeSumBST(TreeNode root, int L, int R) {\n if (root == null) {\n return 0;\n }\n if (root.val >= L && root.val <= R) {\n return root.val + rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R);\n } else if (root.val < L) {\n return rangeSumBST(root.right, L, R);\n } else {\n return rangeSumBST(root.left, L, R);\n }\n }\n}\n```
| 12 | 0 |
[]
| 1 |
range-sum-of-bst
|
Iterative and recursive - doesn't visit every node if possible
|
iterative-and-recursive-doesnt-visit-eve-iic5
|
Complexity\n- Time complexity: O(N) - Number of nodes\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(H) - Height of the tree\n Add your sp
|
savicnikola827
|
NORMAL
|
2024-01-08T00:48:17.520838+00:00
|
2024-01-08T00:48:17.520860+00:00
| 1,055 | false |
# Complexity\n- Time complexity: O(N) - Number of nodes\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(H) - Height of the tree\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Iterative\n```\npublic class Solution {\n public int RangeSumBST(TreeNode root, int low, int high) {\n var count = 0; // number of nodes that satisfy the condition\n var queue = new Queue<TreeNode>(); // recursion representor\n queue.Enqueue(root); // starting with root\n\n while(queue.Count > 0) {\n var current = queue.Dequeue(); // getting current node\n if(current is null) continue; // leaf node - continue\n\n if(current.val < low) {\n // if current value is smaller than low boundary\n // we shouldn\'t keep going left as those values MUST\n // be smaller than low as well so we just go right\n queue.Enqueue(current.right);\n }\n else if(current.val > high) {\n // if current value is greater than high boundary\n // we shouldn\'t keep going right as those values MUST\n // be greater than high as well so we just go left \n queue.Enqueue(current.left);\n }\n else {\n // node value does fall in range \n // so we add it to the sum\n // now, we can keep going both left and right\n // knowing that if current node does fall in range\n // than both of it\'s children may fall \n //in range as well\n count += current.val;\n queue.Enqueue(current.left);\n queue.Enqueue(current.right);\n }\n }\n\n return count;\n }\n}\n```\n# Recursive\n```\npublic class Solution {\n public int RangeSumBST(TreeNode root, int low, int high) {\n int RangeSum(TreeNode current) {\n // same goes here as explained for the iterative approach\n if(current is null) return 0;\n\n if(current.val < low) return RangeSum(current.right);\n else if(current.val > high) return RangeSum(current.left);\n return current.val + RangeSum(current.right) + RangeSum(current.left);\n }\n\n return RangeSum(root);\n }\n}\n```
| 11 | 0 |
['C#']
| 3 |
range-sum-of-bst
|
C++ - Inorder traversal
|
c-inorder-traversal-by-onichan-e58n
|
\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : v
|
onichan
|
NORMAL
|
2019-07-20T16:45:28.486034+00:00
|
2019-07-20T16:45:28.486085+00:00
| 1,731 | false |
```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n int sum = 0;\n \n void inorder(TreeNode* root, int L, int R){\n if(root->left)inorder(root->left, L, R);\n if(root->val>=L && root->val<=R)sum+=root->val;\n if(root->right)inorder(root->right, L, R);\n }\n int rangeSumBST(TreeNode* root, int L, int R) {\n \n //SOLUCHAN STARTS HERE - DUN DUN DUN DUN \n inorder(root, L, R);\n return sum;\n }\n};\n\n```
| 11 | 1 |
['Recursion', 'C']
| 1 |
range-sum-of-bst
|
Python beat 90% simple solution
|
python-beat-90-simple-solution-by-cfaszl-352n
|
\nclass Solution:\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n if not root:\n return 0\n elif root.val >= L and
|
cfaszljr
|
NORMAL
|
2019-05-18T01:03:23.410457+00:00
|
2019-05-18T01:03:23.410520+00:00
| 1,621 | false |
```\nclass Solution:\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n if not root:\n return 0\n elif root.val >= L and root.val <= R:\n return root.val + self.rangeSumBST(root.left, L, R) + self.rangeSumBST(root.right, L, R)\n elif root.val < L:\n return self.rangeSumBST(root.right, L, R)\n else:\n return self.rangeSumBST(root.left, L, R)\n```
| 11 | 0 |
[]
| 2 |
range-sum-of-bst
|
✅ Beats 100% ⚡ | Simple DFS 💡| 7 lines only 😉
|
beats-100-simple-dfs-7-lines-only-by-abd-erkh
|
\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \n All we need is to visit each node, and if it falls in the specified range, incre
|
abdelazizSalah
|
NORMAL
|
2024-01-08T00:12:25.151231+00:00
|
2024-01-08T00:13:14.693517+00:00
| 1,615 | false |
\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n* All we need is to visit each node, and if it falls in the specified range, increment its value with us. \n# Approach\n<!-- Describe your approach to solving the problem. -->\n* This solution is recursive solution\n## Base case\n* if ! root means that we are a child of a leaf node, so just return 0. \n\n## Recursive case\n1. get the value of the left child, by applying recursive call and send the root as the left child.\n2. get the value of the right child, by applying recursive call and send the root as the right child.\n3. if the current value was in the given range inclusive \n 1. return the sum of left, right and the current\n4. else \n 1. return the sum of left and right children only.\n \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n1. O(n) -> the number of nodes.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n1. no auxilary space is needed, but since it is recursive, so it may take O(d) where d is the maximum depth.\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\n #pragma GCC optimize("O3")\n#pragma GCC optimize("Ofast", "inline", "ffast-math", "unroll-loops", "no-stack-protector")\n#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native", "f16c")\nstatic const auto DPSolver = []()\n{ std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return \'c\'; }();\nclass Solution {\npublic:\n Solution(){\n DPSolver;\n }\n int rangeSumBST(TreeNode *root, int low, int high)\n {\n \n // base cases\n if (!root)\n return 0;\n\n int right = rangeSumBST(root->right, low,high); \n int left = rangeSumBST(root->left, low,high); \n if (root->val >= low && root->val <= high )\n return right + left + root->val;\n return right + left ;\n }\n};\n```
| 10 | 1 |
['Tree', 'Depth-First Search', 'Binary Search Tree', 'Recursion', 'Binary Tree', 'C++']
| 4 |
range-sum-of-bst
|
Python 3 (300ms) | Simple DFS | Easy to Understand
|
python-3-300ms-simple-dfs-easy-to-unders-06p1
|
\nclass Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n if root is None:\n return 0\n s=0
|
MrShobhit
|
NORMAL
|
2022-01-27T14:17:36.758707+00:00
|
2022-01-27T14:18:01.219794+00:00
| 823 | false |
```\nclass Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n if root is None:\n return 0\n s=0\n if root.val>=low and root.val<=high:\n s=s+root.val\n s=s+self.rangeSumBST(root.left,low,high)\n s=s+self.rangeSumBST(root.right,low,high)\n return s\n```
| 10 | 0 |
['Depth-First Search', 'Recursion', 'Binary Tree', 'Python', 'Python3']
| 2 |
range-sum-of-bst
|
Java | DFS | BST specific | 0ms | Can merge into one line
|
java-dfs-bst-specific-0ms-can-merge-into-ssc9
|
Original codes:\n\n public int rangeSumBST(TreeNode root, int low, int high) {\n if (root == null)\n \treturn 0;\n int val = 0, left = 0
|
6862wins
|
NORMAL
|
2021-12-14T05:01:24.241381+00:00
|
2021-12-14T05:28:04.156896+00:00
| 1,271 | false |
Original codes:\n```\n public int rangeSumBST(TreeNode root, int low, int high) {\n if (root == null)\n \treturn 0;\n int val = 0, left = 0, right = 0;\n if (root.val >= low && root.val <= high)\n val = root.val;\n if (root.val > low)\n \tleft = rangeSumBST(root.left, low, high);\n if (root.val < high)\n \tright = rangeSumBST(root.right, low, high);\n return val + left + right;\n }\n```\nOne line of codes (seperate to multiple lines for easy-understanding):\n```\n public int rangeSumBST(TreeNode root, int low, int high) {\n \treturn root == null ? 0 :\n \t\t (root.val >= low && root.val <= high ? root.val : 0) +\n \t\t (root.val > low ? rangeSumBST(root.left, low, high) : 0) + \n \t\t (root.val < high ? rangeSumBST(root.right, low, high) : 0);\n }\n
| 10 | 0 |
['Depth-First Search', 'Java']
| 1 |
range-sum-of-bst
|
Jave easy to understand 2ms solution (tree pruning)
|
jave-easy-to-understand-2ms-solution-tre-7pdi
|
\nclass Solution {\n int sum = 0;\n public int rangeSumBST(TreeNode root, int L, int R) {\n helper(root, L, R);\n return sum;\n }\n \n
|
daijidj
|
NORMAL
|
2018-11-14T22:16:49.356957+00:00
|
2018-11-14T22:16:49.356998+00:00
| 3,445 | false |
```\nclass Solution {\n int sum = 0;\n public int rangeSumBST(TreeNode root, int L, int R) {\n helper(root, L, R);\n return sum;\n }\n \n public void helper(TreeNode root, int L, int R){\n if(root == null){\n return;\n }\n if(root.val <= R && root.val >= L){\n sum += root.val;\n helper(root.left, L, R);\n helper(root.right, L, R);\n }else if(root.val < L){\n helper(root.right, L, R); //no need to go left since the left branch must be smaller than L\n }else{ //root great than R\n helper(root.left, L, R); //no need to go right since the right branch must be larger than R\n }\n }\n}\n```
| 10 | 0 |
[]
| 8 |
range-sum-of-bst
|
JavaScript simple DFS solution
|
javascript-simple-dfs-solution-by-i-love-wgik
|
Runtime: 148 ms, faster than 98.20% of JavaScript online submissions for Range Sum of BST.\nMemory Usage: 66.8 MB, less than 100.00% of JavaScript online submis
|
i-love-typescript
|
NORMAL
|
2020-04-15T02:10:51.983700+00:00
|
2020-04-15T02:15:30.836764+00:00
| 1,413 | false |
Runtime: 148 ms, faster than 98.20% of JavaScript online submissions for Range Sum of BST.\nMemory Usage: 66.8 MB, less than 100.00% of JavaScript online submissions for Range Sum of BST.\n```\nfunction rangeSumBST(root, l, r) {\n let sum = 0\n dfs(root)\n return sum\n \n function dfs(node) {\n if (!node) {\n return\n }\n \n if (node.val < l) {\n dfs(node.right)\n return\n }\n \n if (node.val > r) {\n dfs(node.left)\n return\n }\n\n sum += node.val\n dfs(node.left)\n dfs(node.right)\n }\n}\n```
| 9 | 0 |
['JavaScript']
| 1 |
range-sum-of-bst
|
✅ One Line Solution
|
one-line-solution-by-mikposp-tz9w
|
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1 - The Most Concise\nTime complexity: O
|
MikPosp
|
NORMAL
|
2024-01-08T10:41:38.367800+00:00
|
2024-01-09T21:44:05.882537+00:00
| 2,043 | false |
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1 - The Most Concise\nTime complexity: $$O(n)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def rangeSumBST(self, r: Optional[TreeNode], l: int, h: int) -> int:\n return (f:=lambda n:f(n.left)+n.val*(l<=n.val<=h)+f(n.right) if n else 0)(r)\n```\n\n# Code #2 - Simple And Straightforward\nTime complexity: $$O(n)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def rangeSumBST(self, n: Optional[TreeNode], l: int, h: int) -> int:\n return self.rangeSumBST(n.left,l,h)+n.val*(l<=n.val<=h)+self.rangeSumBST(n.right,l,h) if n else 0\n```\n\n# Code #3 - Return Zero Using bool()\nTime complexity: $$O(n)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def rangeSumBST(self, n: Optional[TreeNode], l: int, h: int) -> int:\n return bool(n) and self.rangeSumBST(n.left,l,h)+n.val*(l<=n.val<=h)+self.rangeSumBST(n.right,l,h)\n```\n\n# Code #4 - Return Zero At The End\nTime complexity: $$O(n)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def rangeSumBST(self, n: Optional[TreeNode], l: int, h: int) -> int:\n return n and self.rangeSumBST(n.left,l,h)+n.val*(l<=n.val<=h)+self.rangeSumBST(n.right,l,h) or 0\n```
| 8 | 3 |
['Tree', 'Depth-First Search', 'Binary Tree', 'Python', 'Python3']
| 2 |
range-sum-of-bst
|
✅Easy and Clean Code (C++ / JavaScript)✅✅✅
|
easy-and-clean-code-c-javascript-by-sour-aelt
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
sourav_n06
|
NORMAL
|
2024-01-08T05:29:32.221413+00:00
|
2024-01-08T05:37:32.760957+00:00
| 571 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: Stack Space\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n\n\n# C++\n\n```\nclass Solution {\n void calculateSum(TreeNode* root, int low, int high, int &sum) {\n if(root == NULL) return;\n if(root->val >= low && root->val <= high) sum += root->val;\n calculateSum(root->left, low, high, sum);\n calculateSum(root->right, low, high, sum); \n }\npublic:\n int rangeSumBST(TreeNode* root, int low, int high) {\n int sum = 0;\n calculateSum(root, low, high, sum);\n return sum;\n }\n};\n```\n# JavaScript\n```\nvar sum = 0;\n\nlet calSum = (root, low, high) => {\n if (root == null) return;\n if (root.val >= low && root.val <= high) {\n sum += root.val;\n }\n calSum(root.left, low, high);\n calSum(root.right, low, high);\n}\n\nvar rangeSumBST = function(root, low, high) {\n sum = 0; // Reset sum before each invocation\n calSum(root, low, high);\n return sum;\n};\n\n```\n\n\n
| 8 | 0 |
['Tree', 'Depth-First Search', 'Binary Search Tree', 'Binary Tree', 'C++', 'JavaScript']
| 0 |
range-sum-of-bst
|
Easy C++ recursive solution with Explanation
|
easy-c-recursive-solution-with-explanati-hfq8
|
Approach\n Describe your approach to solving the problem. \nThe function first checks if the root is NULL. If it is, then it returns 0. If the root is not NULL,
|
qwerty-code
|
NORMAL
|
2024-01-08T01:02:26.929033+00:00
|
2024-01-08T01:02:26.929052+00:00
| 1,471 | false |
# Approach\n<!-- Describe your approach to solving the problem. -->\nThe function first checks if the root is NULL. If it is, then it returns 0. If the root is not NULL, the function recursively calls itself for the left and right subtrees, and stores the sum of values in \'left\' and \'right\' variables respectively.\n\nThen, the function checks if the value of the root node falls within the given range. If it does, then it returns the sum of the root node\'s value, \'left\' and \'right\'. If it doesn\'t, then it returns \'left\' and \'right\' sum.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(h)$$ where h is the height of the binary search tree\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int low, int high) {\n if(root == NULL) return 0;\n int left = rangeSumBST(root->left, low, high);\n int right = rangeSumBST(root->right, low, high);\n if(root->val >= low && root->val <= high){\n return root->val + left+right;\n }\n return left+right;\n }\n};\n```
| 8 | 0 |
['C++']
| 0 |
range-sum-of-bst
|
C++ || Using Preorder Traversal || Explained
|
c-using-preorder-traversal-explained-by-91qk9
|
Intuition\nAs we know we need to find the sum between the ranges , so very first thing that comes in our mind is to check all the nodes one by one any try out..
|
mayanksamadhiya12345
|
NORMAL
|
2022-12-07T05:51:27.575018+00:00
|
2022-12-07T05:55:06.962123+00:00
| 757 | false |
# Intuition\nAs we know we need to find the sum between the ranges , so very first thing that comes in our mind is to check all the nodes one by one any try out.... (Using Recursion Do the Traversal)\n\n# Approach\n1. build a rescursive function to call check each node of BST\n2. if my node current value lies under the given ranges then I\'ll take that into my sum\n3. Contuniue calling recursively untill the tree is not finished\n4. Return the sum between ranges\n\n# Complexity\n- **Time complexity: O(n)** -> here n is number of nodes\n\n- **Space complexity: O(n)** -> stack space of recursion\n\n# Code\n```\nclass Solution {\npublic:\n void find(TreeNode* root,int low,int high,int& sum)\n {\n if(root==NULL) return;\n\n if(root->val >= low && root->val <= high) sum += root->val;\n\n find(root->left,low,high,sum);\n find(root->right,low,high,sum);\n }\n int rangeSumBST(TreeNode* root, int low, int high) \n {\n int sum = 0;\n find(root,low,high,sum);\n return sum;\n }\n};\n```
| 8 | 0 |
['Tree', 'Depth-First Search', 'Binary Search Tree', 'Binary Tree', 'C++']
| 0 |
range-sum-of-bst
|
Easy Java Solution using Recursion
|
easy-java-solution-using-recursion-by-de-6vqe
|
\n\n\nclass Solution {\n int sum;\n public int rangeSumBST(TreeNode root, int low, int high) {\n sum = 0;\n rangeSum(root,low,high);\n
|
devesh096
|
NORMAL
|
2022-12-07T05:13:03.417585+00:00
|
2022-12-07T05:13:03.417621+00:00
| 738 | false |
\n\n```\nclass Solution {\n int sum;\n public int rangeSumBST(TreeNode root, int low, int high) {\n sum = 0;\n rangeSum(root,low,high);\n return sum;\n \n }\n \n public void rangeSum(TreeNode root,int low,int high){\n \n if(root != null){\n \n if(low <= root.val && root.val <= high ){\n sum +=root.val;\n }\n if(low < root.val )\n rangeSum(root.left,low,high);\n\n if(root.val <= high )\n rangeSum(root.right,low,high);\n \n \n }\n \n }\n}\n```\n## \n## Please Upvote if it helped.\n## Thanks
| 8 | 2 |
['Binary Search Tree', 'Recursion']
| 1 |
range-sum-of-bst
|
C solution
|
c-solution-by-zhaoyaqiong-kajo
|
\nint rangeSumBST(struct TreeNode* root, int L, int R){\n if (!root) {\n return 0;\n }\n if(root->val<L){\n return rangeSumBST(root->righ
|
zhaoyaqiong
|
NORMAL
|
2020-01-15T01:30:02.295147+00:00
|
2020-01-15T01:30:02.295189+00:00
| 734 | false |
```\nint rangeSumBST(struct TreeNode* root, int L, int R){\n if (!root) {\n return 0;\n }\n if(root->val<L){\n return rangeSumBST(root->right, L, R);\n }\n if(root->val>R){\n return rangeSumBST(root->left, L, R);\n }\n return root->val + rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R);\n}\n```
| 8 | 1 |
[]
| 0 |
range-sum-of-bst
|
Python solution
|
python-solution-by-zitaowang-dc7b
|
DFS recursive:\n\nclass Solution:\n def rangeSumBST(self, root, L, R):\n """\n :type root: TreeNode\n :type L: int\n :type R: int
|
zitaowang
|
NORMAL
|
2018-11-12T04:55:49.392291+00:00
|
2018-11-12T04:55:49.392335+00:00
| 1,699 | false |
DFS recursive:\n```\nclass Solution:\n def rangeSumBST(self, root, L, R):\n """\n :type root: TreeNode\n :type L: int\n :type R: int\n :rtype: int\n """\n def dfs(root):\n if not root:\n return\n if L <= root.val <= R:\n self.res += root.val\n if L <= root.val:\n dfs(root.left)\n if R >= root.val:\n dfs(root.right)\n self.res = 0\n dfs(root)\n return self.res\n```\nDFS iterative:\n```\nclass Solution:\n def rangeSumBST(self, root, L, R):\n """\n :type root: TreeNode\n :type L: int\n :type R: int\n :rtype: int\n """\n stack = [root]\n res = 0\n while stack:\n u = stack.pop()\n if L <= u.val <= R:\n res += u.val\n if u.left and u.val >= L:\n stack.append(u.left)\n if u.right and u.val <= R:\n stack.append(u.right)\n return res\n```
| 8 | 0 |
[]
| 0 |
range-sum-of-bst
|
7th December Daily Challenge LeetCode
|
7th-december-daily-challenge-leetcode-by-gfm3
|
Intuition\nMy Very First intuition to solve this approach was to traverse the tree in inorder manner, I did that and stored values of each Node in a seperate ar
|
rajan_jasani9
|
NORMAL
|
2022-12-07T05:21:48.239826+00:00
|
2022-12-07T06:38:44.132859+00:00
| 530 | false |
# Intuition\nMy Very First intuition to solve this approach was to traverse the tree in inorder manner, I did that and stored values of each Node in a seperate array and then traversed the array to sum up values following the given constraints.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBut then I made a little change in the Inorder Traversal Algorithm and rather than to store in another array I updated the sums variable(variable storing my answer) at that place and then simply returned the sums variable storing my anser.\nNote: I defined a class variable sums to store my answer, so that I can update its value in a helper function findSum from inside the function.\n\nNote: The findSum function I used is simply a modified version of Inorder Traversal Function\n\nVote up if this Helps!\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is same as that of inorder traversal, that is O(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nIf we consider the size of the stack for function calls then O(h + 1) and one is added for sums variable, where h is the height of the tree.\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n\n sums = 0\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n def findSum(root):\n if root:\n findSum(root.left)\n if root.val <= high and root.val >= low:\n self.sums += root.val\n findSum(root.right)\n findSum(root)\n \n return self.sums\n\n```
| 7 | 0 |
['Binary Search Tree', 'Binary Tree', 'Python3']
| 1 |
range-sum-of-bst
|
Daily LeetCoding Challenge (14 December 2021)
|
daily-leetcoding-challenge-14-december-2-2qk5
|
Solution in c++\n\n\n\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int low, int high) {\n \n if(!root) return 0;\n int s
|
spyder_master
|
NORMAL
|
2021-12-14T05:21:28.505989+00:00
|
2021-12-14T05:28:47.225028+00:00
| 451 | false |
**Solution in c++**\n\n```\n\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int low, int high) {\n \n if(!root) return 0;\n int sum = 0;\n if(root->val >= low && root->val <= high) sum += root->val;\n return sum + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high);\n\n }\n};\n```\n**if you understand solution then dont forget to upvote**
| 7 | 2 |
['Binary Search Tree', 'C']
| 1 |
range-sum-of-bst
|
C++ Solution:Recursive,6 lines,easy to understand
|
c-solutionrecursive6-lineseasy-to-unders-ndff
|
If the solution helps,please do consider upvoting it.\n\n\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int low, int high) \n {\n if
|
arceus_1702
|
NORMAL
|
2021-10-30T06:54:06.757687+00:00
|
2021-10-30T06:54:06.757728+00:00
| 533 | false |
**If the solution helps,please do consider upvoting it.**\n\n```\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int low, int high) \n {\n if(!root)\n return 0;\n if(root->val>high)\n return rangeSumBST(root->left,low,high);\n if(root->val<low)\n return rangeSumBST(root->right,low,high);\n return root->val +rangeSumBST(root->left,low,high) +rangeSumBST(root->right,low,high);\n }\n};\n```
| 7 | 0 |
['Recursion', 'C', 'C++']
| 0 |
range-sum-of-bst
|
Java Recursive and Iterative
|
java-recursive-and-iterative-by-hobiter-hdpe
|
\n public int rangeSumBST(TreeNode root, int L, int R) {\n if (root == null) return 0;\n if (root.val <= L) return rangeSumBST(root.right, L, R
|
hobiter
|
NORMAL
|
2020-03-10T20:56:11.006103+00:00
|
2020-03-10T21:21:42.579913+00:00
| 398 | false |
```\n public int rangeSumBST(TreeNode root, int L, int R) {\n if (root == null) return 0;\n if (root.val <= L) return rangeSumBST(root.right, L, R) + (root.val == L ? root.val : 0);\n if (root.val >= R) return rangeSumBST(root.left, L, R) + (root.val == R ? root.val : 0);\n return rangeSumBST(root.left, L, R) + root.val + rangeSumBST(root.right, L, R);\n }\n```\n\n```\n public int rangeSumBST(TreeNode root, int L, int R) {\n Stack<TreeNode> st = new Stack<>();\n st.add(root);\n int sum = 0;\n while (!st.isEmpty()){\n TreeNode n = st.pop();\n if (n == null) continue;\n if (n.val >= L && n.val <= R) sum += n.val;\n if (n.val > L) st.push(n.left);\n if (n.val < R) st.push(n.right);\n }\n return sum;\n }\n```\n
| 7 | 0 |
[]
| 0 |
range-sum-of-bst
|
Easy Processes🔥| Completely Optimised✔| C++✔|Java✔|Python✔|
|
easy-processes-completely-optimised-cjav-jnz1
|
Approach 1 - In-order Traversal with Stack\n# Intuition\nThe goal is to find the sum of values within a given range in a Binary Search Tree (BST). A stack-based
|
Recode_-1
|
NORMAL
|
2024-01-08T02:19:11.613553+00:00
|
2024-01-08T02:19:11.613585+00:00
| 1,602 | false |
# Approach 1 - In-order Traversal with Stack\n# Intuition\nThe goal is to find the sum of values within a given range in a Binary Search Tree (BST). A stack-based iterative approach can efficiently traverse the BST.\n\n# Approach\nWe use a stack to perform an in-order traversal of the BST. At each step, we check if the current node\'s value falls within the specified range [L, R]. If yes, we add it to the sum. We then move to the right subtree if it exists, as we are traversing in-order.\n\n# Complexity\n- Time complexity:O(n)\n - Each node is visited once, where n is the number of nodes in the BST.\n\n- Space complexity:O(h)\n - The space required by the stack is proportional to the height of the BST. In the worst case, when the BST is skewed, it is O(n), but in a balanced BST, it is O(log n).\n\n# C++ Code\n```\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int L, int R) {\n int sum = 0;\n stack<TreeNode*> stk;\n\n while (root != nullptr || !stk.empty()) {\n while (root != nullptr) {\n stk.push(root);\n root = root->left;\n }\n\n root = stk.top();\n stk.pop();\n\n if (root->val >= L && root->val <= R) {\n sum += root->val;\n }\n\n root = root->right;\n }\n\n return sum;\n }\n};\n\n```\n# Java\n```\nimport java.util.Stack;\n\nclass Solution {\n public int rangeSumBST(TreeNode root, int L, int R) {\n int sum = 0;\n Stack<TreeNode> stack = new Stack<>();\n\n while (root != null || !stack.isEmpty()) {\n while (root != null) {\n stack.push(root);\n root = root.left;\n }\n\n root = stack.pop();\n\n if (root.val >= L && root.val <= R) {\n sum += root.val;\n }\n\n root = root.right;\n }\n\n return sum;\n }\n}\n\n```\n# Python \n```\nclass Solution:\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n sum_val = 0\n stack = []\n\n while root or stack:\n while root:\n stack.append(root)\n root = root.left\n\n root = stack.pop()\n\n if L <= root.val <= R:\n sum_val += root.val\n\n root = root.right\n\n return sum_val\n\n```\n\n---\n\n# Approach 2 - Recursive Range Sum\n# Approach\n\n1. Check if the current node is null or the range [L, R] is invalid (L > R), return 0 in such cases.\n2. Compare the value of the current node with L and R.\n - If the value is less than L, explore the right subtree.\n - If the value is greater than R, explore the left subtree.\n - If the value is within the range [L, R], include the current node\'s value in the sum.\n3. Recursively explore both left and right subtrees.\n4. Return the sum of values within the specified range.\n\n# Time Complexity - O(n)\n# Space Complexity - O(H)\n\n# C++ Code\n ```\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int L, int R) {\n if (!root) return 0;\n\n if (root->val < L)\n return rangeSumBST(root->right, L, R);\n\n if (root->val > R)\n return rangeSumBST(root->left, L, R);\n\n return root->val + rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R);\n }\n};\n\n```\n# Java\n```\npublic class Solution {\n public int rangeSumBST(TreeNode root, int L, int R) {\n if (root == null || L > R) {\n return 0;\n }\n\n if (root.val < L) {\n return rangeSumBST(root.right, L, R);\n }\n\n if (root.val > R) {\n return rangeSumBST(root.left, L, R);\n }\n\n return root.val + rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R);\n }\n}\n```\n# Python \n```\nclass Solution:\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n if not root or L > R:\n return 0\n\n if root.val < L:\n return self.rangeSumBST(root.right, L, R)\n\n if root.val > R:\n return self.rangeSumBST(root.left, L, R)\n\n return root.val + self.rangeSumBST(root.left, L, R) + self.rangeSumBST(root.right, L, R)\n\n```\n
| 6 | 1 |
['Tree', 'Depth-First Search', 'Binary Search Tree', 'Binary Tree', 'Python', 'C++', 'Java', 'Python3']
| 0 |
range-sum-of-bst
|
✅C++ | ✅Inorder Traversal | ✅Intuitive Approach
|
c-inorder-traversal-intuitive-approach-b-72y1
|
Intuition\nInorder traversal of BST returns nodes in sorted order.\n\n# Approach\nWhile sorting nodes by using inorder traversal, we sum up all the nodes values
|
Yash2arma
|
NORMAL
|
2022-12-07T05:09:54.256420+00:00
|
2022-12-07T05:11:58.590267+00:00
| 1,127 | false |
# Intuition\nInorder traversal of BST returns nodes in sorted order.\n\n# Approach\nWhile sorting nodes by using inorder traversal, we sum up all the nodes values lies between the range.\n\n# Complexity\n- Time complexity: O(N) \n\n- Space complexity: O(N)\n\n# Code\n```\nclass Solution \n{\npublic:\n void inorder(TreeNode* node, int &low, int &high, int &sum)\n {\n if(!node) return;\n inorder(node->left, low, high, sum);\n if(node->val >= low && node->val <= high) sum += node->val;\n inorder(node->right, low, high, sum);\n }\n int rangeSumBST(TreeNode* root, int low, int high) \n {\n int sum=0;\n inorder(root, low, high, sum);\n return sum; \n }\n};\n```
| 6 | 0 |
['Depth-First Search', 'Binary Search Tree', 'Recursion', 'C++']
| 0 |
range-sum-of-bst
|
C++| EASY TO UNDERSTAND| Iterative| O(n) time-complexity
|
c-easy-to-understand-iterative-on-time-c-4k4s
|
Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, i
|
aarindey
|
NORMAL
|
2021-05-24T11:41:24.102165+00:00
|
2021-05-24T11:41:57.819421+00:00
| 297 | false |
**Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)**\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int low, int high) {\n if(root==NULL)\n return 0;\n int sum=0;\n if(root->val<=high&&root->val>=low)\n {\n sum+=root->val;\n }\n if(root->val>high)\n {\n sum+=rangeSumBST(root->left,low,high);\n }\n else if(root->val<low)\n {\n sum+=rangeSumBST(root->right,low,high);\n }\n else\n {\n sum+=rangeSumBST(root->right,low,high)+rangeSumBST(root->left,low,high);\n }\n return sum;\n }\n};
| 6 | 1 |
['Binary Search Tree', 'C', 'Iterator']
| 1 |
range-sum-of-bst
|
Python 🐍 | Easy Explanation | 2 Methods
|
python-easy-explanation-2-methods-by-hri-2038
|
\nPlatform: leetcode.com\n938. Range Sum of BST\nLink: https://leetcode.com/problems/range-sum-of-bst/\nDifficulty: Easy\nAuthor: hritik5102\nDate: 17/1/2021\nS
|
hritik5102
|
NORMAL
|
2021-01-17T15:59:01.536174+00:00
|
2021-01-17T16:06:15.176157+00:00
| 725 | false |
```\nPlatform: leetcode.com\n938. Range Sum of BST\nLink: https://leetcode.com/problems/range-sum-of-bst/\nDifficulty: Easy\nAuthor: hritik5102\nDate: 17/1/2021\nSubmission: https://leetcode.com/submissions/detail/444136335/\n(Time, Space) Complexity : O(n), O(H)\n\nRange sum of BST \n\n1. We can solve this problem using recursion and iteration \n\niteration Recursion \n1. implemented using loops 1. implemented using function calls \n2. Defined by the control variable 2. Defined by the parameter value in the stack\nvalue \n3. iteration makes size of Code 3. Recursion decreses the size of code\nbigger \n4. Loop ends when control variable 4. Recursion ends when base case are True\nsatisfy the condition \n5. Infinite loops uses CPU Cycle 5. Infinite Recursion cause stack overflow at particular point or might crash the system\n6. Execution is faster 6. Execution is slower\n```\n\n# Method 01 \n# Inorder traversal ( Left child , Node , Right child)\n\n**Disadvantage of using Inorder traversal method**\n\n1. Using this approach we are visiting at each node of the binary tree and we are not utilizing the benefit of binary tree.\n\n2. Time: O(n), space: O(h), where n is the number of total nodes, h is the height of the tree.\n\n\n```\nclass Solution: \n def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:\n output = []\n if root==None:\n return 0\n self.inOrderTraversal(root,low,high,output)\n return sum(output) \n \n def inOrderTraversal(self, root,low,high,output):\n if root == None:\n return\n\t\t\n\t\t# Left \n self.inOrderTraversal(root.left, low,high,output)\n\t\t\n\t\t# Node \n if low <= root.val <= high:\n output.append(root.val)\n\t\t\t\n\t\t# Right\n self.inOrderTraversal(root.right, low,high,output)\n\n```\n\nSo what we do when we search a particular number in a binary tree\n\nfirst we check if a number is less then a root, if yes then we search in left subtree else if it\'s greater then we search in right subtree of root node\n\nsame here, we see \n```\n1. if low < root :\n\t\t inOrderTraversal( root.left, low, high)\n\n2. if High > root :\n\t\t inOrderTraversal( root.right, low, high) \n```\n\n# Method 02 \n```\nclass Solution: \n def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:\n output = []\n if root==None:\n return 0\n self.inOrderTraversal(root,low,high,output)\n return sum(output) \n \n def inOrderTraversal(self, root,low,high,output):\n if root == None:\n return\n\t\t\t\n\t\t# left \n if low<root.val:\n self.inOrderTraversal(root.left, low,high,output)\n\t\t\n\t\t# Node\n if low <= root.val <= high:\n output.append(root.val)\n\t\t\n\t\t# RIght \n if high>root.val:\n self.inOrderTraversal(root.right, low,high,output)\n```\n\n# Method 03 \n## Same Logic but reduction in line of code\n```\nclass Solution: \n def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:\n total = 0\n if root==None:\n return 0\n if low <= root.val <= high:\n total +=root.val\n if low<root.val:\n total += self.rangeSumBST(root.left, low,high)\n if high>root.val:\n total += self.rangeSumBST(root.right, low,high)\n \n return total \n```\n\n \n
| 6 | 0 |
['Python']
| 2 |
range-sum-of-bst
|
[Java] DFS & BFS - With explanation
|
java-dfs-bfs-with-explanation-by-allenju-4hkf
|
DFS\n\nclass Solution {\n public int rangeSumBST(TreeNode root, int low, int high) {\n if(root == null)\n return 0;\n int sum = root
|
allenjue
|
NORMAL
|
2020-11-18T04:49:25.732236+00:00
|
2020-11-18T05:31:44.404967+00:00
| 745 | false |
**DFS**\n```\nclass Solution {\n public int rangeSumBST(TreeNode root, int low, int high) {\n if(root == null)\n return 0;\n int sum = root.val <= high && root.val >= low ? root.val : 0;\n int left = 0;\n int right = 0;\n if(root.left != null){\n left = rangeSumBST(root.left,low,high);\n } \n if(root.right != null){\n right = rangeSumBST(root.right, low, high);\n }\n return sum + left + right;\n }\n}\n```\n**BFS**\n```\nclass Solution {\n public int rangeSumBST(TreeNode root, int low, int high) {\n if(root == null)\n return 0;\n Queue<TreeNode> q = new LinkedList<TreeNode>();\n q.add(root); // add root node\n int sum = 0;\n while(!q.isEmpty()){\n int itr = q.size();\n while(itr > 0){\n TreeNode dummy = q.poll();\n sum += (dummy.val >= low && dummy.val <= high) ? dummy.val : 0;\n if(dummy.left != null)\n q.add(dummy.left);\n if(dummy.right != null)\n q.add(dummy.right);\n itr--;\n }\n }\n\t\treturn sum;\n\t}\n}\n```\n \n**PROBLEM OVERVIEW**\nWe are essentially tasked with finding the sum of all nodes whose values are between the inclusive range [low,high].\n\n**SOLUTION ASSESSMENT**\nThe first things that come to mind are any tree-traversla algorithms (I have an inclination to utilize DFS or BFS, and I will show both approaches)\n\n**PSEUDOCODE RECURSION DFS**\n```\npublic int rangeSumBST(TreeNode root, int low, int high) {\n1. If(root == null) return 0;\n2. sum = node.val if within [low,high] : 0;\n3. int leftSum = rangeSum(node.left,low,high); //left node\n4. int rightSum = rangeSum(node.right,low,high); //right node\n5. return sum + leftSum + rightSum\n}\n```\n\nThe heart of this solution lies with the recursive calls in lines 3-4. It will essentially visit all the nodes in the left branch and* return the leftSum* and all the right nodes in the branch and return the rightSum. Finally, the answer will be the current node + left + right.\n\n**PSUEDOCODE ITERATIVE BFS**\n```\n1. if root is null return 0; // corner case\n2. initialize Queue<TreeNode> q and int sum\n3. add root to q\n4. while q is not empty {\n\t5. itr = q.size() // this is because the current "size" is the # of elements in that row\n\t6. while itr > 0\n\t\t7. get node from list and add to answer if sum is in range\n\t\t8. add left and right nodes if they exist\n}\n9. return sum\n```\nIn the BFS solution, the current Queue of TreeNodes is read in FIFO order, so it maintains an order (not that it matters in this problem). \nThe key steps lie in 5 and 7-8; for 5 regulates the number of iterations in that particular "row" of the tree, which is the current size of the Queue. Line 7-8 add the children of that current row in left -> order.\n\n**TIME COMPLEXITY**\nThe code for both runs in O(n) time complexity because it always visits every node.\nNOTE: even though BFS solution has nested while loops, they are only called a maximum of n times, where n is the number of nodes in the tree.\n\n\n
| 6 | 0 |
['Tree', 'Recursion', 'Java']
| 1 |
range-sum-of-bst
|
2 JavaScript solutions
|
2-javascript-solutions-by-liadove-sey5
|
You need to return sum of values in range of numbers between L and R. Not between nodes of L and R\n\nvar rangeSumBST = function(root, L, R, sum=0) {\n if(!r
|
liadove
|
NORMAL
|
2020-04-17T22:58:06.440287+00:00
|
2020-04-17T22:58:06.440335+00:00
| 584 | false |
You need to return sum of values in range of numbers between L and R. Not between nodes of L and R\n```\nvar rangeSumBST = function(root, L, R, sum=0) {\n if(!root) return sum;\n if(root.val<=R && root.val>=L)\n sum += root.val;\n return sum + rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R);\n};\n\nvar rangeSumBST = function(root, L, R, sum=0) {\n let stack = [root];\n while(stack.length){\n let node = stack.pop();\n sum+=node.val>=L &&node.val<=R ? node.val : 0;\n if(node.left)\n stack.push(node.left);\n if(node.right)\n stack.push(node.right);\n }\n return sum;\n};\n```
| 6 | 0 |
['Recursion', 'JavaScript']
| 0 |
range-sum-of-bst
|
C++ Easy, Fast, and Understandable
|
c-easy-fast-and-understandable-by-paular-01g2
|
\nRuntime: 144 ms, faster than 86.30% of C++ online submissions for Range Sum of BST.\nMemory Usage: 41 MB, less than 100.00% of C++ online submissions for Rang
|
paulariri
|
NORMAL
|
2020-01-03T11:26:24.448115+00:00
|
2020-01-03T11:26:24.448151+00:00
| 1,160 | false |
```\nRuntime: 144 ms, faster than 86.30% of C++ online submissions for Range Sum of BST.\nMemory Usage: 41 MB, less than 100.00% of C++ online submissions for Range Sum of BST.\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int L, int R) {\n int counter = 0;\n \n rangeSum(root, counter, L, R);\n \n return counter;\n }\n \n void rangeSum(TreeNode* root, int& counter, int L, int R){\n \n if(root->val >= L && root->val <= R){\n counter += root->val;\n }\n if(root->left != NULL){\n rangeSum(root->left, counter, L, R);\n }\n if(root->right != NULL){\n rangeSum(root->right, counter, L, R);\n }\n }\n};\n```
| 6 | 0 |
['Recursion', 'C', 'Binary Tree']
| 0 |
range-sum-of-bst
|
Sum of BST Values in a Given Range
|
sum-of-bst-values-in-a-given-range-by-ta-pkhz
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThe code aims to find the sum of values in a binary search tree (BST) that fall within
|
tanmay656565
|
NORMAL
|
2024-01-08T02:26:59.311906+00:00
|
2024-01-08T02:26:59.311928+00:00
| 1,515 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code aims to find the sum of values in a binary search tree (BST) that fall within a specified range [low, high]. It uses a preorder traversal to explore the tree, collecting node values into a list, and then sums up the values within the given range.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTraverse the BST using preorder traversal.\nCollect all node values in the ans list.\nIterate through the list and sum up values within the specified range [low, high].\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n ans = []\n def preorder(root) :\n if not root :\n return \n ans.append(root.val)\n preorder(root.left)\n preorder(root.right)\n preorder(root)\n sol = 0\n for i in ans :\n if (low <= i <= high) :\n sol += i\n return sol \n \n \n```
| 5 | 1 |
['Python3']
| 1 |
range-sum-of-bst
|
My first Shared Solution
|
my-first-shared-solution-by-abdelrhmanka-lj1a
|
My first time sharing a Solution\nI hope it helps you.\n# Approach\nOnly using Recursion.\n\n# Complexity\n- Time complexity: O(N)\n- Space complexity: O(1)\n#
|
abdelrhmankaram
|
NORMAL
|
2024-01-08T02:22:59.719772+00:00
|
2024-01-08T02:25:21.493634+00:00
| 478 | false |
# My first time sharing a Solution\nI hope it helps you.\n# Approach\nOnly using Recursion.\n\n# Complexity\n- Time complexity: O(N)\n- Space complexity: O(1)\n# C++ Code\n```\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int low, int high) {\n return (in(root->val, low, high) ? root->val : 0)\n +\n (root->left != nullptr ? rangeSumBST(root->left, low, high) : 0)\n +\n (root->right != nullptr ? rangeSumBST(root->right, low, high) : 0);\n }\n bool in(int x, int low, int high){\n return x >= low && x <= high;\n }\n};\n```\n\n# Python Code\n```\n class Solution(object):\n def rangeSumBST(self, root, low, high):\n num = root.val if root.val >= low and root.val <= high else 0\n return num + (self.rangeSumBST(root.right, low, high) if root.right else 0) + (self.rangeSumBST(root.left, low, high) if root.left else 0)\n```
| 5 | 0 |
['Python', 'C++']
| 0 |
range-sum-of-bst
|
MOST EASY PREORDER SOLUTION || EASY TO UNDERSTAND || C++
|
most-easy-preorder-solution-easy-to-unde-bsc0
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
hr_188
|
NORMAL
|
2024-01-08T02:04:19.241888+00:00
|
2024-01-08T02:04:19.241921+00:00
| 406 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n int sum;\n void rec(TreeNode* root, int low, int high){\n if(root==NULL) return ;\n if(root->val <= high && root-> val >= low){\n sum += root->val;\n }\n rec(root->left , low,high);\n rec(root->right , low , high);\n }\n int rangeSumBST(TreeNode* root, int low, int high) {\n sum = 0;\n rec(root, low,high);\n return sum;\n }\n};\n```
| 5 | 0 |
['C++']
| 0 |
range-sum-of-bst
|
Simple tree traversal
|
simple-tree-traversal-by-donpaul271-d0i5
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nTraverse the whole tree and check if the value is within range. If yes, t
|
donpaul271
|
NORMAL
|
2024-01-08T00:08:23.601027+00:00
|
2024-01-08T00:12:16.280581+00:00
| 266 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTraverse the whole tree and check if the value is within range. If yes, then add it to the result.\n\n(Please upvote if it helped)\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nint res;\n\nvoid traverse(TreeNode* node, int low, int high)\n{\n if(node->val >=low && node->val <= high)\n res+=node->val;\n\n if(node->left != NULL)\n traverse(node->left, low, high);\n\n if(node->right != NULL)\n traverse(node->right, low, high);\n}\n\nclass Solution {\npublic:\n int rangeSumBST(TreeNode* root, int low, int high) {\n\n res = 0;\n traverse(root, low, high);\n return res;\n }\n};\n```
| 5 | 0 |
['C++']
| 0 |
range-sum-of-bst
|
Java | 2 lines | Simple | Clean code
|
java-2-lines-simple-clean-code-by-judgem-kcrx
|
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co
|
judgementdey
|
NORMAL
|
2024-01-08T00:05:42.641021+00:00
|
2024-01-08T00:05:42.641047+00:00
| 720 | false |
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int rangeSumBST(TreeNode node, int low, int high) {\n if (node == null) return 0;\n \n return (node.val >= low && node.val <= high ? node.val : 0) +\n (low < node.val ? rangeSumBST(node.left, low, high) : 0) +\n (high > node.val ? rangeSumBST(node.right, low, high) : 0);\n }\n}\n\n```\nIf you like my solution, please upvote it!
| 5 | 0 |
['Depth-First Search', 'Binary Search Tree', 'Java']
| 1 |
range-sum-of-bst
|
Python Binary Search Tree || Beats 92% ||
|
python-binary-search-tree-beats-92-by-sa-raad
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
saim75
|
NORMAL
|
2023-10-25T04:12:18.999298+00:00
|
2023-10-25T04:12:18.999317+00:00
| 212 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n def inOrderTraversal(node):\n nonlocal total_sum\n if not node:\n return\n if low <= node.val <= high:\n total_sum += node.val\n if node.val > low:\n inOrderTraversal(node.left)\n if node.val < high:\n inOrderTraversal(node.right)\n\n total_sum = 0\n inOrderTraversal(root)\n return total_sum\n```
| 5 | 0 |
['Binary Search Tree', 'Python3']
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.