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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
check-if-the-number-is-fascinating | Python3 Solution | python3-solution-by-motaharozzaman1996-hgk1 | \n\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n return sorted(str(n)+str(2*n)+str(3*n))==list(map(str,range(1,10)))\n | Motaharozzaman1996 | NORMAL | 2023-06-10T17:04:44.322669+00:00 | 2023-06-10T17:04:44.322714+00:00 | 150 | false | \n```\nclass Solution:\n def isFascinating(self, n: int) -> bool:\n return sorted(str(n)+str(2*n)+str(3*n))==list(map(str,range(1,10)))\n``` | 1 | 0 | ['Python', 'Python3'] | 0 |
check-if-the-number-is-fascinating | Very Simple Solution!!! | very-simple-solution-by-yashpadiyar4-9tpp | \n\n# Code\n\nclass Solution {\npublic:\n bool isFascinating(int n) {\n string s=to_string(n);\n string s1=to_string(2*n);\n string s2=t | yashpadiyar4 | NORMAL | 2023-06-10T16:04:29.744832+00:00 | 2023-06-10T16:04:29.744869+00:00 | 389 | false | \n\n# Code\n```\nclass Solution {\npublic:\n bool isFascinating(int n) {\n string s=to_string(n);\n string s1=to_string(2*n);\n string s2=to_string(3*n);\n string s3=s+s1+s2;\n vector<int>vis(10000,0);\n for(int i=0;i<s3.size();i++){\n vis[s3[i]-\'0\']++;\n }\n if(vis[0])return false;\n for(int i=1;i<9999;i++){\n if(vis[i]>1)return false;\n }\n return true;\n \n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
check-if-the-number-is-fascinating | Check if The Number is Fascinating | check-if-the-number-is-fascinating-by-sa-c3bv | IntuitionThe key observation is that a fascinating number, when concatenated with its multiples 2n and 3n, must contain each of the digits 1 through 9 exactly o | sania_sial | NORMAL | 2025-04-11T06:24:27.733982+00:00 | 2025-04-11T06:24:27.733982+00:00 | 1 | false | 
# Intuition
The key observation is that a fascinating number, when concatenated with its multiples 2n and 3n, must contain each of the digits 1 through 9 exactly once. By concatenating these values and then sorting the resulting string, we can verify if it equals "123456789".
# Approach
**1. Concatenation:** Convert the number n, 2n, and 3n into strings and concatenate them.
**2. Sorting:** Sort the concatenated string.
**3. Verification:** Compare the sorted result with "123456789". If they match, then the number is fascinating; otherwise, it is not.
# Complexity
- Time complexity: O(1)
- Space complexity: O(1)
# Code
```python3 []
class Solution:
def isFascinating(self, n: int) -> bool:
num = str(n) + str(2 * n) + str(3 * n)
return "".join(sorted(num)) == "123456789"
``` | 0 | 0 | ['Math', 'Python3'] | 0 |
check-if-the-number-is-fascinating | Python Easy Solution | python-easy-solution-by-vini__7-5emd | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Vini__7 | NORMAL | 2025-04-07T16:32:28.393685+00:00 | 2025-04-07T16:32:28.393685+00:00 | 3 | 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
```python3 []
class Solution:
def isFascinating(self, n: int) -> bool:
a=2*n
b=3*n
c=str(n)+str(a)+str(b)
set1=set(c)
return len(c)==len(set1) and "0" not in c
``` | 0 | 0 | ['Python3'] | 0 |
check-if-the-number-is-fascinating | Luke - is fascinating solution | luke-is-fascinating-solution-by-thunderl-o8nl | IntuitionApproachI used 3 int variables. One of them is the int n value, the other is n2, while the other is n3. I converted all these 3 int variables to string | thunderlukey | NORMAL | 2025-04-06T18:33:58.145483+00:00 | 2025-04-06T18:33:58.145483+00:00 | 3 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
I used 3 int variables. One of them is the int n value, the other is n*2, while the other is n*3. I converted all these 3 int variables to strings. I combined these three strings to one string, whose variable name is answer. I declared nine more int variables in order for me to keep the number os 1s,2s,3s,4s,5s,6s,7s,8s,and 9s. If the string contains 0, return false. We check to see if there are exactly one of 1s,2s,3s,4s,5s,6s,7s,8s,and 9s.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean isFascinating(int n) {
int first = n;
int second = n*2;
int third = n*3;
String o = Integer.toString(first);
String t = Integer.toString(second);
String r = Integer.toString(third);
String answer = o+t+r;
int ones = 0;
int twos = 0;
int threes = 0;
int fours = 0;
int fives = 0;
int sixes = 0;
int sevens = 0;
int eights = 0;
int nines = 0;
for (int i=0; i<answer.length(); i++){
if (answer.charAt(i) == '0'){
return false;
}
else if (answer.charAt(i) == '1'){
ones++;
}
else if (answer.charAt(i) == '2'){
twos++;
}
else if (answer.charAt(i) == '3'){
threes++;
}
else if (answer.charAt(i) == '4'){
fours++;
}
else if (answer.charAt(i) == '5'){
fives++;
}
else if (answer.charAt(i) == '6'){
sixes++;
}
else if (answer.charAt(i) == '7'){
sevens++;
}
else if (answer.charAt(i) == '8'){
eights++;
}
else if (answer.charAt(i) == '9'){
nines++;
}
}
return ones == 1 && twos == 1 && threes == 1 && fours == 1 && fives == 1 && sixes == 1 && sevens == 1 && eights == 1 && nines == 1;
}
}
``` | 0 | 0 | ['Java'] | 0 |
check-if-the-number-is-fascinating | alternative solution using numbers and sets | alternative-solution-using-numbers-and-s-8u0k | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | dpasala | NORMAL | 2025-04-04T02:56:44.484563+00:00 | 2025-04-04T02:56:44.484563+00:00 | 3 | 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
```java []
class Solution {
public boolean isFascinating(int n1) {
int n2 = n1 * 2;
int n3 = n1 * 3;
Set<Integer> set = new HashSet<>();
for (int i = 1; i <= 9; i++) set.add(i);
while (n1 > 0) {
if (!set.remove(n1 % 10)) return false;
n1 /= 10;
}
while (n2 > 0) {
if (!set.remove(n2 % 10)) return false;
n2 /= 10;
}
while (n3 > 0) {
if (!set.remove(n3 % 10)) return false;
n3 /= 10;
}
return set.size() == 0;
}
}
``` | 0 | 0 | ['Number Theory', 'Ordered Set', 'Java'] | 0 |
check-if-the-number-is-fascinating | beats 80% runtime (stringbuilder solution) | beats-80-runtime-stringbuilder-solution-31393 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | dpasala | NORMAL | 2025-04-04T02:53:13.379330+00:00 | 2025-04-04T02:53:13.379330+00:00 | 3 | 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
```java []
class Solution {
public boolean isFascinating(int n) {
StringBuilder sb = new StringBuilder();
sb.append(n);
sb.append(n * 2);
sb.append(n * 3);
Set<Character> set = new HashSet<>();
for (char c = '1'; c <= '9'; c++) set.add(c);
for (char c : sb.toString().toCharArray()){
if (!set.remove(c)) return false;
}
return set.size() == 0;
}
}
``` | 0 | 0 | ['Java'] | 0 |
check-if-the-number-is-fascinating | Check if The Number is Fascinating | check-if-the-number-is-fascinating-by-su-r7uy | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | suyunovshohjahon08 | NORMAL | 2025-04-03T01:41:02.686452+00:00 | 2025-04-03T01:41:02.686452+00:00 | 1 | 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
```typescript []
function isFascinating(n: number): boolean {
const concatenated = `${n}${n * 2}${n * 3}`;
return concatenated.length === 9 && new Set(concatenated).size === 9 && !concatenated.includes('0');
}
``` | 0 | 0 | ['TypeScript'] | 0 |
check-if-the-number-is-fascinating | Concatenation solution | concatenation-solution-by-ezpectus-pm9i | Approach:Concatenate the numbers:We use string interpolation ($"{n}{n * 2}{n * 3}") to create the concatenated string.
Check the length:
The concatenated string | ezpectus | NORMAL | 2025-03-31T22:51:49.723321+00:00 | 2025-03-31T22:51:49.723321+00:00 | 2 | false |
Approach:
Concatenate the numbers:
We use string interpolation ($"{n}{n * 2}{n * 3}") to create the concatenated string.
Check the length:
The concatenated string must have a length of 9.
Check for '0':
The concatenated string must not contain the digit '0'.
Check for unique digits:
The concatenated string must contain all 9 unique digits (1 to 9).
Complexity:
Time Complexity: O(1). The operations are performed on a fixed number of digits.
Space Complexity: O(1). The concatenated string's size is fixed.
# Code
```csharp []
public class Solution {
public bool IsFascinating(int n) {
string concatenated = $"{n}{n * 2}{n * 3}";
return concatenated.Length == 9 &&
!concatenated.Contains('0') &&
concatenated.Distinct().Count() == 9;
}
}
``` | 0 | 0 | ['Hash Table', 'Math', 'C#'] | 0 |
check-if-the-number-is-fascinating | C++ math approach, string concatenation w/ a set, and the optimal solution | c-math-approach-string-concatenation-w-a-0f5m | Math Approach (no strings)Note: Since n is an integer from [100, 999] we don't have to check for n == 0 thus a log10 function is good since n > 0.
For this to w | iwat1874 | NORMAL | 2025-03-31T08:20:45.133945+00:00 | 2025-03-31T08:20:45.133945+00:00 | 3 | false | # Math Approach (no strings)
<!-- Describe your approach to solving the problem. -->
**Note:** Since n is an integer from [100, 999] we don't have to check for n == 0 thus a log10 function is good since n > 0.
1) For this to work, we need to either check if the 3n is a 4 digit number and if it is, we return false.
2) To get our total number, we can just do 1_000_000 * n + 1_000 * 2n + 3n = 1_002_003n. This will be sure to place the digits in the correct spots for each 3 digit number.
3) initialize an array (digit counter) and keep count of all the digits in the total.
4) Check if 1-9 appear only once
5) check if there is any 0 in the arr, if there is return false if not return true
# String concatination approach:
1) Concat the strings n + n*2 + n*3.
2) Check if the length of the string is 9. Only way for 9 digits to appear once and no zero.
3) Initialize a set with all the digits in it.
4) if the set is {'1', '2', '3', '4', '5', '6', '7', '8', '9'}, then return true. (hence checking that the size is 9) But if there is a 0 at all, return false.
# Last approach:
1) if n is any of these numbers in the set {192, 219, 273, 327} then it is true, else false.
**NOTE**: I found this out from just making a loop from 100-999 inclusive since these are the constraints and find that these are the only numbers that satisfy this problem.
# Time and space complexity:
- Time complexity: O(1)
Since at most we iterate 9 times. O(9) -> O(1)
- Space Complexity: O(1)
# Code
```cpp []
// mathematical solution (no strings)
class Solution {
public:
bool isFascinating(int n) {
if(floor(log10(n * 3)) + 1 >= 4){
return false;
}
int total = 1002003 * n;
int arr[10] = {0};
while(total > 0){
arr[total % 10]++;
total /= 10;
}
for(int i = 1; i < 10; i++){
if(arr[i] > 1 || arr[i] == 0){
return false;
}
}
return arr[0] == 0;
}
};
// string concatination solution
class Solution {
public:
bool isFascinating(int n) {
std::string concat_num = to_string(n) + to_string(n * 2) + to_string(n * 3);
if(concat_num.length() != 9){
return false;
}
set<char> set1(concat_num.begin(), concat_num.end());
return set1.find('0') == set1.end() && set1.size() == 9;
}
};
// best solution
class Solution {
public:
bool isFascinating(int n) {
return n == 192 || n == 219 || n == 273 || n == 327;
}
};
``` | 0 | 0 | ['C++'] | 0 |
check-if-the-number-is-fascinating | Simple code beats 100% with comments | simple-code-beats-100-with-comments-by-r-tzsw | IntuitionNo idea at firstApproachWe just check if there are zeros, duplicates, and the length is 9. If all True then return True. Else return FalseComplexity
Ti | RandomUser3456 | NORMAL | 2025-03-30T22:20:09.913342+00:00 | 2025-03-30T22:20:09.913342+00:00 | 5 | false | # Intuition
No idea at first
# Approach
We just check if there are zeros, duplicates, and the length is 9. If all True then return True. Else return False
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def isFascinating(self, n: int) -> bool:
"""Combine the Nums"""
num = str(n) + str(2*n) + str(3*n)
"""Setting the variables"""
noduplicate = True
new = []
"""if there are 2 of the same nums in the number, noduplicate = False"""
for digit in num:
if digit in new:
noduplicate = False
new.append(digit)
"""Checks if zero is in num"""
zero_in_num = ('0' in num) == False
"""Final if statement"""
if len(num) == 9 and zero_in_num and noduplicate == True:
return True
else:
return False
``` | 0 | 0 | ['Python3'] | 0 |
check-if-the-number-is-fascinating | Fast no comment (no time to explain version) | fast-no-comment-no-time-to-explain-versi-529y | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | RandomUser3456 | NORMAL | 2025-03-30T22:16:39.361633+00:00 | 2025-03-30T22:16:39.361633+00:00 | 2 | 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
```python3 []
class Solution:
def isFascinating(self, n: int) -> bool:
num = str(n)+str(2*n)+str(3*n)
abc = True
new = []
for digit in num:
if digit in new:
abc = False
new.append(digit)
true = ('0' in num) == False
if len(num)==9 and true and abc == True:
return True
else:
return False
``` | 0 | 0 | ['Python3'] | 0 |
check-if-the-number-is-fascinating | 2-line fascinating solution | 2-line-fascinating-solution-by-mleo8-nith | Code | mleo8 | NORMAL | 2025-03-27T17:35:52.213300+00:00 | 2025-03-27T17:35:52.213300+00:00 | 2 | false | # Code
```python3 []
class Solution:
def isFascinating(self, n: int) -> bool:
s = str(n) + str(n * 2) + str(n * 3)
return len(s) == 9 and set(s) == set("123456789")
```
| 0 | 0 | ['Python3'] | 0 |
check-if-the-number-is-fascinating | 🔥✅✅ Dart Solution 📌📌 || with Explanation 👌👌 | dart-solution-with-explanation-by-nosar-76xe | Solution
Numbers that produce concatenated results with incorrect lengths (either too short or too long)
Numbers that contain zeros in any of n, 2n, or 3n
Numbe | NosaR | NORMAL | 2025-03-27T01:45:41.860828+00:00 | 2025-03-27T01:45:41.860828+00:00 | 3 | false | # Solution
- Numbers that produce concatenated results with incorrect lengths (either too short or too long)
- Numbers that contain zeros in any of n, 2n, or 3n
- Numbers that have duplicate digits in the concatenated result
- Numbers that don't cover all digits from 1-9
### Time Complexity:
**Overall Time Complexity**: O(1) - All operations are constant time since the input size is fixed (n is always a 3-digit number and the concatenated result is at most 9 digits).
```dart
class Solution {
bool isFascinating(int n) {
String concatenated = '$n${2 * n}${3 * n}';
if (concatenated.length != 9) {
return false;
}
if (concatenated.contains('0')) {
return false;
}
Set<String> digits = {};
for (int i = 0; i < concatenated.length; i++) {
String digit = concatenated[i];
if (digits.contains(digit)) {
return false;
}
digits.add(digit);
}
return digits.length == 9;
}
}
``` | 0 | 0 | ['Dart'] | 0 |
check-if-the-number-is-fascinating | another variant | another-variant-by-mattwix-fnjk | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | MatTwix | NORMAL | 2025-03-22T20:50:31.624977+00:00 | 2025-03-22T20:50:31.624977+00:00 | 1 | 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
```golang []
func isFascinating(n int) bool {
var digits[10] int
str := strconv.Itoa(n) + strconv.Itoa(n * 2) + strconv.Itoa(n * 3)
for _, el := range str {
digits[el - '0']++
}
var one int
for idx, el := range digits {
one = el
if one != 1 && idx != 0 || idx == 0 && one != 0 { return false }
}
return true
}
``` | 0 | 0 | ['Go'] | 0 |
check-if-the-number-is-fascinating | Easy to understand solution in Java. | easy-to-understand-solution-in-java-by-k-azql | Complexity
Time complexity:
O(logn)
Space complexity:
O(logn)
Code | Khamdam | NORMAL | 2025-03-21T07:45:30.950399+00:00 | 2025-03-21T07:45:30.950399+00:00 | 4 | false | # Complexity
- Time complexity:
O(logn)
- Space complexity:
O(logn)
# Code
```java []
class Solution {
public boolean isFascinating(int n) {
StringBuilder sb = new StringBuilder();
String concat = sb.append(n).append(2 * n).append(3 * n).toString();
int m = concat.length();
int[] freq = new int[m+1];
for (char c : concat.toCharArray()) {
int digit = Integer.parseInt(String.valueOf(c));
freq[digit]++;
}
for (int i = 1; i <= 9; i++) {
if (freq[i] != 1) {
return false;
}
}
if (freq[0] > 0) {
return false;
}
return true;
}
}
``` | 0 | 0 | ['Java'] | 0 |
check-if-the-number-is-fascinating | Easy Approach | easy-approach-by-kunal_1310-lo3o | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | kunal_1310 | NORMAL | 2025-03-20T08:33:37.778041+00:00 | 2025-03-20T08:33:37.778041+00:00 | 3 | 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
```cpp []
class Solution {
public:
bool isFascinating(int n) {
string s=to_string(n)+to_string(2*n)+to_string(3*n);
if(s.size()>9)return false;
vector<int> r;
for(int i=0;i<9;i++){
r.push_back(s[i]-'0');
}
sort(r.begin(),r.end());
for(int i=0;i<9;i++){
if(r[i]!=i+1){
return false;
}
}
return true;
}
};
``` | 0 | 0 | ['C++'] | 0 |
check-if-the-number-is-fascinating | using python | using-python-by-bhabanisbiswal-imjc | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | bhabanisbiswal | NORMAL | 2025-03-15T14:35:04.942823+00:00 | 2025-03-15T14:35:04.942823+00:00 | 2 | 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
```python []
class Solution(object):
def isFascinating(self, n):
x=[]
for i in range(1,4):
a=n*i
for i in str(a):
if i not in x:
x.append(int(i))
for i in range(1,10):
if i not in x:
return False
for i in x:
if x.count(i)>1:
return False
return True
``` | 0 | 0 | ['Python'] | 0 |
check-if-the-number-is-fascinating | Runtime: 0 ms, Beats 100% | runtime-0-ms-beats-100-by-singhalearn03-s3s3 | IntuitionThe problem requires checking whether a given three-digit number n satisfies the fascinating number property. The key observation here is that a fascin | singhalearn03 | NORMAL | 2025-03-12T07:35:08.612079+00:00 | 2025-03-12T07:35:08.612079+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem requires checking whether a given three-digit number n satisfies the fascinating number property. The key observation here is that a fascinating number, when concatenated with its twice and thrice multiples, should form a 9-digit sequence containing digits 1-9 exactly once without any 0s.
Given the constraints, we can efficiently verify the fascinating condition by:
- Concatenating n, 2 * n, and 3 * n.
- Ensuring the length of the resulting string is exactly 9.
- Checking if all digits from 1-9 appear exactly once.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Compute n1 = 2 * n and n2 = 3 * n.
2. Convert n, n1, and n2 to strings and concatenate them.
3. Check if the concatenated string has exactly 9 characters.
4. Verify that all digits from 1-9 appear exactly once in the concatenated string.
5. Return True if the number meets the conditions; otherwise, return False.
# Complexity
- Time complexity: O(1)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
Since n is always a three-digit number, operations like string concatenation, length check, and digit presence verification run in constant time.
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
We use only a few integer variables and a string, which take constant space.
# Code
```python []
class Solution(object):
def isFascinating(self, n):
"""
:type n: int
:rtype: bool
"""
n1 = n * 2
n2 = n * 3
res = str(n) + str(n1) + str(n2)
if len(res)>9:
return False
for i in range(1, 10):
if str(i) not in res:
return False
return True
``` | 0 | 0 | ['Python'] | 0 |
check-if-the-number-is-fascinating | Super easy to understand solution -->> Beats 100.00% | super-easy-to-understand-solution-beats-64buz | IntuitionApproachComplexity
Time complexity:
O(n)
Space complexity:
O(1)
Code | DevelopersUsername | NORMAL | 2025-03-07T18:05:10.300127+00:00 | 2025-03-07T18:05:10.300127+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:
O(n)
- Space complexity:
O(1)
# Code
```java []
class Solution {
public boolean isFascinating(int n) {
int[] count = new int[10];
for (int i = 1; i < 4; i++)
fascinating(n * i, count);
if (count[0] != 0) return false;
for (int i = 1; i < count.length; i++)
if (count[i] != 1) return false;
return true;
}
private static void fascinating(int n, int[] count) {
while (n > 0) {
count[n % 10]++;
n /= 10;
}
}
}
``` | 0 | 0 | ['Java'] | 0 |
check-if-the-number-is-fascinating | python beats 100% speed | python-beats-100-speed-by-adamliewehr-cciz | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | adamliewehr | NORMAL | 2025-02-25T00:16:20.186296+00:00 | 2025-02-25T00:16:20.186296+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
```python3 []
class Solution:
def isFascinating(self, n: int) -> bool:
concat = list(str(n)+str(2*n)+str(3*n))
concat.sort()
concat = "".join(concat)
if concat == "123456789":
return True
else:
return False
``` | 0 | 0 | ['Python3'] | 0 |
check-if-the-number-is-fascinating | Easy and Simple C++ using Strings. | easy-and-simple-c-using-strings-by-mishr-7duj | IntuitionThis is a easy problem you just have to change the type of data structure. That's it for thisApproach
First Calculate the Multiplication with 2 and 3 a | mishrasuyash013 | NORMAL | 2025-02-22T21:20:54.303385+00:00 | 2025-02-22T21:20:54.303385+00:00 | 4 | false | # Intuition
This is a easy problem you just have to change the type of data structure. That's it for this
# Approach
- First Calculate the Multiplication with 2 and 3 and store them.
- Then Convert these into String Using the to_String() function.
- Then declare 2 string one is empty and other with number from 1 to 9.
- Sort the answer string and just compare the 2 strings with each other and break the loop if at some index the values are mismatched
# Code
```cpp []
class Solution {
public:
bool isFascinating(int n) {
int a = 2 * n;
int b = 3 * n;
string alen = to_string(a);
string blen = to_string(b);
string nlen = to_string(n);
string res = alen + blen + nlen;
string exp = "123456789";
sort(res.begin(), res.end());
for (int i = 0; i <= res.length(); i++) {
if (res[i] != exp[i]) {
return false;
break;
}
}
return true;
}
};
``` | 0 | 0 | ['C++'] | 0 |
check-if-the-number-is-fascinating | 100% beats solution | 100-beats-solution-by-yashchandola12-opp6 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | yashchandola12 | NORMAL | 2025-02-22T13:18:29.026448+00:00 | 2025-02-22T13:18:29.026448+00:00 | 2 | 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
```python []
class Solution(object):
def isFascinating(self, n):
a="123456789"
t=str(n)+str(n*2)+str(n*3)
f=sorted(t)
k=''.join(f)
return a==k
``` | 0 | 0 | ['Python'] | 0 |
check-if-the-number-is-fascinating | Beats 100% time and space || Simple C++ Solution | beats-100-time-and-space-simple-c-soluti-rqc4 | IntuitionApproachComplexity
Time complexity: O(N)
Space complexity: O(1)
Code | Devanshv123 | NORMAL | 2025-02-20T14:37:12.484292+00:00 | 2025-02-20T14:37:12.484292+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: O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
bool check(int n){
bool checkZero = false;
while(n>0){
if(n%10==0){
checkZero = true;
break;
}
n /= 10;
}
return checkZero;
}
void func(int n, vector<int> &v){
while(n>0){
v[(n%10) - 1]++;
n /= 10;
}
}
bool isFascinating(int n) {
if(check(n) || check(2*n) || check(3*n)){
return false;
}
vector<int> v(9,0);
func(n, v);
func(2*n, v);
func(3*n, v);
for(int i=0; i<9; i++){
if(v[i]==1) continue;
else return false;
}
return true;
}
};
``` | 0 | 0 | ['Hash Table', 'Math', 'C++'] | 0 |
check-if-the-number-is-fascinating | BEATS 100% EASY PYTHON CODE | beats-100-easy-python-code-by-vishnuande-luaa | Code | vishnuande2006 | NORMAL | 2025-02-08T14:51:21.975596+00:00 | 2025-02-08T14:51:21.975596+00:00 | 3 | false |
# Code
```python3 []
class Solution:
def isFascinating(self, n: int) -> bool:
a = n*2
b = n*3
c =str(n)+str(a)+str(b)
d = "123456789"
if len(c)!=9:
return False
for i in d:
if i not in c:
return False
return True
``` | 0 | 0 | ['Python3'] | 0 |
check-if-the-number-is-fascinating | Super Easy Solution | Beginner Friendly | Beats 100% | super-easy-solution-beginner-friendly-be-olzl | Code | udaisaikiran | NORMAL | 2025-02-07T18:50:52.253993+00:00 | 2025-02-07T18:50:52.253993+00:00 | 2 | false |
# Code
```python3 []
class Solution:
def isFascinating(self, n: int) -> bool:
res=""
d="123456789"
res+=str(n)+str(2*n)+str(3*n)
if len(res)!=9:
return False
for i in d:
if i not in res:
return False
return True
``` | 0 | 0 | ['Python3'] | 0 |
check-if-the-number-is-fascinating | Simple Java Solution | simple-java-solution-by-gopika_kathir-h3t3 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Gopika_kathir | NORMAL | 2025-02-06T10:33:13.435417+00:00 | 2025-02-06T10:33:13.435417+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
```java []
class Solution {
public boolean isFascinating(int n) {
int num=2;
String s=n+"";
while(s.length()<9){
s=s+(n*num)+"";
num++;
}
int[] dp=new int[10];
for(int i=0;i<s.length();i++){
int g=s.charAt(i)-'0';
dp[g]++;
}
for(int i=1;i<=9;i++){
if(dp[i]!=1)
return false;
}
return true;
}
}
``` | 0 | 0 | ['Java'] | 0 |
check-if-the-number-is-fascinating | easy | easy-by-hemu1817-9ybj | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | hemu1817 | NORMAL | 2025-02-05T16:47:19.616237+00:00 | 2025-02-05T16:47:19.616237+00:00 | 3 | 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
```python []
class Solution(object):
def isFascinating(self, n):
n1=2*n
n2=3*n
a=str(n)+str(n1)+str(n2)
sort=sorted(a)
if sort==list("123456789"):
return True
return False
``` | 0 | 0 | ['Python'] | 0 |
check-if-the-number-is-fascinating | TIME COMPLEXITY - O(1) | time-complexity-o1-by-its_gokhul-84xj | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | its_gokhul | NORMAL | 2025-02-01T14:37:34.528155+00:00 | 2025-02-01T14:37:34.528155+00:00 | 3 | 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
```java []
class Solution {
public boolean isFascinating(int n) {
String one = Integer.toString(n);
String two = Integer.toString(n * 2);
String three = Integer.toString(n * 3);
String s = one + two + three;
char[] charArr = s.toCharArray();
Arrays.sort(charArr);
String str = new String(charArr);
return str.equals("123456789");
}
}
``` | 0 | 0 | ['Java'] | 0 |
check-if-the-number-is-fascinating | easy java solution using for loop | easy-java-solution-using-for-loop-by-cha-fad6 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | chandan_kr1 | NORMAL | 2025-01-31T17:34:19.573551+00:00 | 2025-01-31T17:34:19.573551+00:00 | 5 | 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
```java []
class Solution {
public boolean isFascinating(int n) {
String s= n+""+n*2+""+n*3;
int[] arr=new int[10];
for(int i=0;i<s.length();i++)
{
char c = s.charAt(i);
arr[c-48]++;
}
for(int i=1;i<arr.length;i++)
{
if(arr[i]!=1)
return false;
}
return true;
}
}
``` | 0 | 0 | ['Java'] | 0 |
check-if-the-number-is-fascinating | [C++] Simple Solution | c-simple-solution-by-samuel3shin-zrqz | Code | Samuel3Shin | NORMAL | 2025-01-28T16:05:00.010045+00:00 | 2025-01-28T16:05:00.010045+00:00 | 5 | false |
# Code
```cpp []
class Solution {
public:
vector<int> v;
void helper(int n) {
while(n > 0) {
v[n%10]++;
n/=10;
}
}
bool isFascinating(int n) {
v.resize(10, 0);
int n2 = n*2;
int n3 = n*3;
helper(n);
helper(n2);
helper(n3);
if(v[0] > 0) return false;
for(int i=1; i<10; i++) {
if(v[i] != 1) return false;
}
return true;
}
};
``` | 0 | 0 | ['C++'] | 0 |
check-if-the-number-is-fascinating | Python 3 - Beats 100 - Super Simple | python-3-beats-100-super-simple-by-zacha-t5xn | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | zacharylupstein | NORMAL | 2025-01-28T15:40:07.032320+00:00 | 2025-01-28T15:40:07.032320+00:00 | 2 | 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
```python3 []
class Solution:
def isFascinating(self, n: int) -> bool:
numMap = {}
doubled = n * 2
tripled = n * 3
stringVersion = str(n) + str(doubled) + str(tripled)
for char in stringVersion:
if char in numMap:
return False
numMap[char] = True
for i in range(1, 10):
if str(i) not in numMap:
return False
return True
``` | 0 | 0 | ['Python3'] | 0 |
check-if-the-number-is-fascinating | C++ 0ms 100% without string, sort... | c-0ms-100-without-string-sort-by-fredo30-0e4d | Code | fredo30400 | NORMAL | 2025-01-25T17:54:22.728234+00:00 | 2025-01-25T17:54:22.728234+00:00 | 3 | false |
# Code
```cpp []
class Solution {
public:
bool isFascinating(int n) {
if(n>329)return false; // if over two 3(before 333) or more than 9 numbers
int a = 2*n;
int b = 3*n;
n = n*1000000+a*1000+b; //insert all 9 numbers in n
int numbers[10]={0}; //for counting each numbers 0 to 9
while (n!=0){
numbers[n%10]++;// put each number of n in numbers
n /= 10;
}
if(numbers[0]>0)return false; // no zero
for(int i=1;i<10;i++){
if(numbers[i]!=1)return false; // each number one time only
}
return true;
}
};
``` | 0 | 0 | ['C++'] | 0 |
path-sum | [Accepted]My recursive solution in Java | acceptedmy-recursive-solution-in-java-by-xvzx | The basic idea is to subtract the value of current node from sum until it reaches a leaf node and the subtraction equals 0, then we know that we got a hit. Othe | boy27910230 | NORMAL | 2014-09-05T14:40:54+00:00 | 2018-10-25T18:37:28.662873+00:00 | 109,182 | false | The basic idea is to subtract the value of current node from sum until it reaches a leaf node and the subtraction equals 0, then we know that we got a hit. Otherwise the subtraction at the end could not be 0.\n\n public class Solution {\n public boolean hasPathSum(TreeNode root, int sum) {\n if(root == null) return false;\n \n if(root.left == null && root.right == null && sum - root.val == 0) return true;\n \n return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);\n }\n } | 697 | 7 | [] | 75 |
path-sum | Short Python recursive solution - O(n) | short-python-recursive-solution-on-by-go-5d28 | # Definition for a binary tree node\n # class TreeNode:\n # def __init__(self, x):\n # self.val = x\n # self.left = None\n # | google | NORMAL | 2015-03-21T06:33:10+00:00 | 2018-10-23T16:18:36.347201+00:00 | 56,005 | false | # 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 \n class Solution:\n # @param root, a tree node\n # @param sum, an integer\n # @return a boolean\n # 1:27\n def hasPathSum(self, root, sum):\n if not root:\n return False\n \n if not root.left and not root.right and root.val == sum:\n return True\n \n sum -= root.val\n \n return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum) | 442 | 2 | ['Python'] | 65 |
path-sum | 3 lines of c++ solution | 3-lines-of-c-solution-by-pankit-sbzi | bool hasPathSum(TreeNode *root, int sum) {\n if (root == NULL) return false;\n if (root->val == sum && root->left == NULL && root->right | pankit | NORMAL | 2015-03-06T13:40:43+00:00 | 2018-10-17T17:44:43.794599+00:00 | 51,242 | false | bool hasPathSum(TreeNode *root, int sum) {\n if (root == NULL) return false;\n if (root->val == sum && root->left == NULL && root->right == NULL) return true;\n return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);\n } | 419 | 4 | [] | 32 |
path-sum | ✅Easy Solution🔥Python3/C/C#/C++/Java🔥Explain Line By Line🔥With🗺️Image🗺️ | easy-solutionpython3cccjavaexplain-line-zwis1 | Problem\nYou\'re given a binary tree and an integer targetSum. The task is to determine whether there exists a root-to-leaf path in the tree where the sum of th | MrAke | NORMAL | 2023-08-29T19:13:26.143600+00:00 | 2023-08-29T19:13:26.143621+00:00 | 48,257 | false | # Problem\nYou\'re given a binary tree and an integer targetSum. The task is to determine whether there exists a root-to-leaf path in the tree where the sum of the values of the nodes along the path equals the targetSum.\n\nIn other words, you need to check if there\'s a sequence of nodes starting from the root and following edges to reach a leaf node such that the sum of values along this path is equal to the given targetSum.\n\n\n---\n# Solution\nThe provided solution is implemented as a method named hasPathSum within a class named Solution. The method takes two parameters: root, which is the root node of the binary tree, and targetSum, the desired sum.\n\n\n**Here\'s how the solution works:** \n\n1. f root is None (i.e., the tree is empty), there can\'t be any path with the desired sum. So, the function returns False.\n2. If root is a leaf node (i.e., it has no left or right children), the function checks whether the value of the leaf node is equal to the remaining targetSum. If they are equal, it returns True, indicating that a valid path with the target sum has been found.\n3. If the above conditions are not met, the function recursively checks for a valid path with the target sum in both the left and right subtrees. It subtracts the value of the current node from the targetSum before passing it to the recursive calls.\n4. The result of the recursive calls on the left and right subtrees (left_sum and right_sum) are then combined using the logical OR operation. This is because if either the left subtree or the right subtree has a valid path, it means there\'s a valid path in the entire tree, so the function should return True.\n5. If none of the above conditions are met, the function returns False.\n\nThe base cases (when the tree is empty or when a leaf node with a matching value is found) guarantee that the recursion will eventually terminate. The recursion explores all possible paths from the root to leaf nodes, checking if any of them sum up to the given targetSum. The logical OR operation on the results of the recursive calls ensures that the function correctly returns True if a valid path is found anywhere in the tree.\n\nThis solution has a time complexity of O(N), where N is the number of nodes in the binary tree, as it visits each node once in the worst case.\n\n\n\n\n# Code\n---\n\n```Python3 []\nclass Solution:\n def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n if not root:\n return False\n \n if not root.left and not root.right:\n return targetSum == root.val\n \n left_sum = self.hasPathSum(root.left, targetSum - root.val)\n right_sum = self.hasPathSum(root.right, targetSum - root.val)\n \n return left_sum or right_sum\n```\n```python []\nclass Solution:\n def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n if not root:\n return False\n \n if not root.left and not root.right:\n return targetSum == root.val\n \n left_sum = self.hasPathSum(root.left, targetSum - root.val)\n right_sum = self.hasPathSum(root.right, targetSum - root.val)\n \n return left_sum or right_sum\n```\n```C# []\npublic class Solution\n{\n public bool HasPathSum(TreeNode root, int targetSum)\n {\n if (root == null)\n {\n return false;\n }\n\n if (root.left == null && root.right == null)\n {\n return targetSum == root.val;\n }\n\n bool leftSum = HasPathSum(root.left, targetSum - root.val);\n bool rightSum = HasPathSum(root.right, targetSum - root.val);\n\n return leftSum || rightSum;\n }\n}\n```\n\n```C++ []\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int targetSum) {\n if (!root) {\n return false;\n }\n \n if (!root->left && !root->right) {\n return targetSum == root->val;\n }\n \n bool left_sum = hasPathSum(root->left, targetSum - root->val);\n bool right_sum = hasPathSum(root->right, targetSum - root->val);\n \n return left_sum || right_sum;\n }\n};\n```\n```Java []\nclass Solution {\n public boolean hasPathSum(TreeNode root, int targetSum) {\n if (root == null) {\n return false;\n }\n \n if (root.left == null && root.right == null) {\n return targetSum == root.val;\n }\n \n boolean leftSum = hasPathSum(root.left, targetSum - root.val);\n boolean rightSum = hasPathSum(root.right, targetSum - root.val);\n \n return leftSum || rightSum;\n }\n}\n``` | 400 | 1 | ['C', 'Python', 'C++', 'Java', 'Python3', 'C#'] | 9 |
path-sum | Python solutions (DFS recursively, DFS+stack, BFS+queue) | python-solutions-dfs-recursively-dfsstac-kb5v | DFS Recursively \n def hasPathSum1(self, root, sum):\n res = []\n self.dfs(root, sum, res)\n return any(res)\n \n def dfs(self | oldcodingfarmer | NORMAL | 2015-07-11T09:10:26+00:00 | 2020-09-06T15:38:43.498369+00:00 | 32,389 | false | # DFS Recursively \n def hasPathSum1(self, root, sum):\n res = []\n self.dfs(root, sum, res)\n return any(res)\n \n def dfs(self, root, target, res):\n if root:\n if not root.left and not root.right and root.val == target:\n res.append(True)\n if root.left:\n self.dfs(root.left, target-root.val, res)\n if root.right:\n self.dfs(root.right, target-root.val, res)\n \n # DFS with stack\n def hasPathSum2(self, root, sum):\n if not root:\n return False\n stack = [(root, root.val)]\n while stack:\n curr, val = stack.pop()\n if not curr.left and not curr.right and val == sum:\n return True\n if curr.right:\n stack.append((curr.right, val+curr.right.val))\n if curr.left:\n stack.append((curr.left, val+curr.left.val))\n return False\n \n # BFS with queue\n def hasPathSum(self, root, sum):\n if not root:\n return False\n queue = [(root, sum-root.val)]\n while queue:\n curr, val = queue.pop(0)\n if not curr.left and not curr.right and val == 0:\n return True\n if curr.left:\n queue.append((curr.left, val-curr.left.val))\n if curr.right:\n queue.append((curr.right, val-curr.right.val))\n return False\n\t\t\n\tdef hasPathSum1(self, root, sum):\n if not root:\n return False\n if not root.left and not root.right and root.val == sum:\n return True\n return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val) | 238 | 0 | ['Stack', 'Depth-First Search', 'Breadth-First Search', 'Queue', 'Python'] | 21 |
path-sum | [C++] Recursive solution {4 lines code} | c-recursive-solution-4-lines-code-by-shu-3m9x | Pls upvote if you find this helpful :)\n\nThree things to remember while solving any recursion based questions are:\n1)Terminating condition/Base Case\n2)Body | shubhambhatt__ | NORMAL | 2020-06-04T18:06:49.709737+00:00 | 2020-06-04T18:07:37.290284+00:00 | 16,732 | false | ***Pls upvote if you find this helpful :)***\n\nThree things to remember while solving any recursion based questions are:\n1)Terminating condition/Base Case\n2)Body (Code to be performed each time)\n3)Propagation(Calling itself,propagating further)\n```\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int sum) {\n if(!root)return false; //Terminating Condition\n sum=sum-root->val; //Body\n if(sum==0&&!root->left&&!root->right)return true; //body\n return hasPathSum(root->left,sum)||hasPathSum(root->right,sum);//Propagation\n }\n};\n``` | 214 | 2 | ['Recursion', 'C', 'C++'] | 9 |
path-sum | Easiest Beginner Friendly Sol || Recursion || O(n) time and O(h) space | easiest-beginner-friendly-sol-recursion-f4m0q | Intuition\n- We are using top down recursion approach to solve this problem.\n- See below solution to understand how we can use top down and bottom up approach | singhabhinash | NORMAL | 2023-01-25T05:01:47.621123+00:00 | 2023-01-25T05:05:51.466771+00:00 | 27,019 | false | # Intuition\n- We are using **top down recursion** approach to solve this problem.\n- See below solution to understand how we can use top down and bottom up approach in recursion.\nhttps://leetcode.com/problems/maximum-depth-of-binary-tree/solutions/3093043/easiest-beginner-friendly-solution-dfs-o-n-time-and-o-h-space/?orderBy=hot\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Create a helper function called "rootToLeafPathSum" that takes in three parameters: a binary tree node, a target sum, and a current sum.\n2. Check if the current node is null, and if so, return false.\n3. Check if the current node is a leaf node (i.e. has no left or right children), and if so, add the value of the node to the current sum.\n4. If the current sum equals the target sum, return true.\n5. Recursively call the "rootToLeafPathSum" function on the left and right children of the current node, passing in the updated current sum.\n6. Return the result of the recursive calls.\n7. In the "hasPathSum" function, initialize the current sum to 0 and call the "rootToLeafPathSum" function on the root node, passing in the target sum and current sum as parameters.\n8. Return the result of the "rootToLeafPathSum" function call.\n<!-- Describe your approach to solving the problem. -->\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 */\nclass Solution {\npublic:\n bool rootToLeafPathSum(TreeNode* root, int targetSum, int sum){\n if(root == nullptr)\n return false;\n if(root -> left == nullptr && root -> right == nullptr){\n sum = sum + root -> val;\n if(sum == targetSum)\n return true; \n }\n return rootToLeafPathSum(root -> left, targetSum, sum + root -> val) || rootToLeafPathSum(root -> right, targetSum, sum + root -> val);\n }\n bool hasPathSum(TreeNode* root, int targetSum) {\n int sum = 0;\n return rootToLeafPathSum(root, targetSum, sum);\n }\n};\n```\n```Java []\nclass Solution {\n public boolean rootToLeafPathSum(TreeNode root, int targetSum, int sum){\n if(root == null)\n return false;\n if(root.left == null && root.right == null){\n sum = sum + root.val;\n if(sum == targetSum)\n return true; \n }\n return rootToLeafPathSum(root.left, targetSum, sum + root.val) || rootToLeafPathSum(root.right, targetSum, sum + root.val);\n }\n public boolean hasPathSum(TreeNode root, int targetSum) {\n int sum = 0;\n return rootToLeafPathSum(root, targetSum, sum);\n }\n}\n\n```\n```Python []\nclass Solution:\n def rootToLeafPathSum(self, root: TreeNode, targetSum: int, sum: int) -> bool:\n if root is None:\n return False\n if root.left is None and root.right is None:\n sum += root.val\n if sum == targetSum:\n return True \n return self.rootToLeafPathSum(root.left, targetSum, sum + root.val) or self.rootToLeafPathSum(root.right, targetSum, sum + root.val)\n\n def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:\n sum = 0\n return self.rootToLeafPathSum(root, targetSum, sum)\n\n```\n- If my solution is helpful to you then please **UPVOTE** my solution, your **UPVOTE** motivates me to post such kind of solution.\n- Please let me know in comments if there is need to do any improvement in my approach, code....anything.\n- **Let\'s connect on** https://www.linkedin.com/in/abhinash-singh-1b851b188\n\n\n# Complexity\n- Time complexity: **O(n)** // where n is the number of nodes in the tree\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:**O(h)** //where h is the height of the tree\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> | 151 | 1 | ['Binary Tree', 'Python', 'C++', 'Java'] | 6 |
path-sum | Java solution, both recursion and iteration | java-solution-both-recursion-and-iterati-4v7i | \n public boolean hasPathSum(TreeNode root, int sum) {\n // iteration method\n if (root == null) {return false;}\n Stack path = new Stac | young_stone | NORMAL | 2015-07-19T17:07:29+00:00 | 2018-10-22T19:41:08.863591+00:00 | 15,583 | false | \n public boolean hasPathSum(TreeNode root, int sum) {\n // iteration method\n if (root == null) {return false;}\n Stack<TreeNode> path = new Stack<>();\n Stack<Integer> sub = new Stack<>();\n path.push(root);\n sub.push(root.val);\n while (!path.isEmpty()) {\n TreeNode temp = path.pop();\n int tempVal = sub.pop();\n if (temp.left == null && temp.right == null) {if (tempVal == sum) return true;}\n else {\n if (temp.left != null) {\n path.push(temp.left);\n sub.push(temp.left.val + tempVal);\n }\n if (temp.right != null) {\n path.push(temp.right);\n sub.push(temp.right.val + tempVal);\n }\n }\n }\n return false;\n }\n\n\n----------\n\n public boolean hasPathSum(TreeNode root, int sum) {\n // recursion method\n if (root == null) return false;\n if (root.left == null && root.right == null && root.val == sum) return true;\n return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);\n } | 88 | 1 | ['Java'] | 12 |
path-sum | [Accepted] By using postorder traversal | accepted-by-using-postorder-traversal-by-c826 | In the postorder traversal, the node will be removed from the stack only when the right sub-tree has been visited.so the path will be stored in the stack. we ca | sjames | NORMAL | 2014-07-28T03:16:52+00:00 | 2018-10-12T15:32:40.437983+00:00 | 24,779 | false | In the postorder traversal, the node will be removed from the stack only when the right sub-tree has been visited.so the path will be stored in the stack. we can keep check the SUM, the length from root to leaf node.\nat leaf node, if SUM == sum, OK, return true. After postorder traversal, return false.\n\nI have compared this solution with recursion solutions. In the leetcode OJ, the run time of two solutions is very near.\n\nbelow is my iterator code.\n\n\n class Solution {\n public:\n bool hasPathSum(TreeNode *root, int sum) {\n stack<TreeNode *> s;\n TreeNode *pre = NULL, *cur = root;\n int SUM = 0;\n while (cur || !s.empty()) {\n while (cur) {\n s.push(cur);\n SUM += cur->val;\n cur = cur->left;\n }\n cur = s.top();\n if (cur->left == NULL && cur->right == NULL && SUM == sum) {\n return true;\n }\n if (cur->right && pre != cur->right) {\n cur = cur->right;\n } else {\n pre = cur;\n s.pop();\n SUM -= cur->val;\n cur = NULL;\n }\n }\n return false;\n }\n }; | 75 | 2 | ['Iterator'] | 20 |
path-sum | ✅C++ || BEATS 95% || EASY || EXPLAINED || OPTIMIZED | c-beats-95-easy-explained-optimized-by-a-sojx | PLEASE UPVOTE IF YOU FIND MY APPROACH HELPFUL, MEANS A LOT \uD83D\uDE0A\n\nQues) Why we return left || right ???\nAns => return left || right means we are check | ayushsenapati123 | NORMAL | 2022-10-04T04:25:35.632590+00:00 | 2022-10-04T04:34:03.673033+00:00 | 7,039 | false | **PLEASE UPVOTE IF YOU FIND MY APPROACH HELPFUL, MEANS A LOT \uD83D\uDE0A**\n\n**Ques)** Why we `return left || right` ???\n**Ans =>** `return left || right` means we are checking either root->left side gives us our targetSum or root->right side gives us our targetSum\n\n```\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int targetSum)\n {\n if(root == NULL)\n {\n return false;\n }\n if(root->left == NULL && root->right == NULL && root->val - targetSum == 0)\n {\n return true;\n }\n \n bool left = hasPathSum(root->left,targetSum - root->val);\n bool right = hasPathSum(root->right,targetSum - root->val);\n \n return left || right;\n }\n};\n```\n\n | 74 | 0 | ['Tree', 'Recursion', 'C++'] | 3 |
path-sum | My java no-recursive method | my-java-no-recursive-method-by-scott-mhrg | the idea is preorder traverse , instead of using recursive call, I am using a stack.\nthe only problem is that I changed TreeNode value\n\n public boolean ha | scott | NORMAL | 2015-01-17T05:12:26+00:00 | 2018-09-20T06:13:09.864089+00:00 | 13,788 | false | the idea is preorder traverse , instead of using recursive call, I am using a stack.\nthe only problem is that I changed TreeNode value\n\n public boolean hasPathSum(TreeNode root, int sum) {\n \t Stack <TreeNode> stack = new Stack<> ();\t \n \t stack.push(root) ;\t \n \t while (!stack.isEmpty() && root != null){\n \t \tTreeNode cur = stack.pop() ;\t\n \t \tif (cur.left == null && cur.right == null){\t \t\t\n \t \t\tif (cur.val == sum ) return true ;\n \t \t}\n \t \tif (cur.right != null) {\n \t \t\tcur.right.val = cur.val + cur.right.val ;\n \t \t\tstack.push(cur.right) ;\n \t \t}\n \t \tif (cur.left != null) {\n \t \t\tcur.left.val = cur.val + cur.left.val;\n \t \t\tstack.push(cur.left);\n \t \t}\n \t }\t \n \t return false ;\n \t } | 65 | 1 | [] | 6 |
path-sum | Simplest C++ solution. EASY to understand. | simplest-c-solution-easy-to-understand-b-v2v1 | \nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int targetSum)\n {\n if(root == NULL)\n {\n return false;\n | kfaisal-se | NORMAL | 2021-06-20T10:10:57.652991+00:00 | 2021-06-20T10:10:57.653033+00:00 | 6,087 | false | ```\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int targetSum)\n {\n if(root == NULL)\n {\n return false;\n }\n if(root->left == NULL && root->right == NULL && root->val - targetSum == 0)\n {\n return true;\n }\n \n bool left = hasPathSum(root->left,targetSum - root->val);\n bool right = hasPathSum(root->right,targetSum - root->val);\n \n return left || right;\n }\n};\n```\n**Like the solution?\nPlease upvote \u30C4**\n\nIf you can\'t understand any step/point, feel free to comment.\nHappy to help. | 56 | 2 | ['Recursion', 'C', 'C++'] | 2 |
path-sum | One Line Solution Sharing in Javascript | one-line-solution-sharing-in-javascript-f95vu | Since this problem is quite straight forward, so I played around a bit and turned it into the shortest solution as below.\n\n /*\n * Memo:\n * Comple | imcoddy | NORMAL | 2015-06-02T12:22:35+00:00 | 2015-06-02T12:22:35+00:00 | 5,304 | false | Since this problem is quite straight forward, so I played around a bit and turned it into the shortest solution as below.\n\n /**\n * Memo:\n * Complex: O(n)\n * Runtime: 164ms\n * Tests: 114 test cases passed\n * Rank: A\n */\n var hasPathSum = function(root, sum) { return root ? (!root.left && !root.right) ? sum === root.val : (hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val)) : false; };\n\nWhile it is equivalent as the following\n \n var hasPathSum = function(root, sum) {\n if (!root) return false;\n\n if (!root.left && !root.right) { // check leaf\n return sum === root.val;\n } else { // continue DFS\n return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);\n }\n }; | 56 | 2 | ['Recursion', 'JavaScript'] | 7 |
path-sum | [Python] BFS, DFS (recursive), DFS (iterative) solution | python-bfs-dfs-recursive-dfs-iterative-s-wij7 | I. DFS recursive solution\nAlgorithm:\n1. Visit a node and check that node is leaf and node.val == sum. If it\'s true - return True, else continue traverse\n2. | rgalyeon | NORMAL | 2020-03-09T10:27:07.475788+00:00 | 2020-03-09T10:29:19.383990+00:00 | 5,329 | false | #### I. DFS recursive solution\nAlgorithm:\n1. Visit a node and check that node is leaf and node.val == sum. If it\'s true - return True, else continue traverse\n2. Traverse the left subtree and decrease current sum by value of current node , i.e., call `hasPathSum(node.left, curr_sum - node.val)`\n3. Traverse the right subtree and decrease current sum by value of current node , i.e., call `hasPathSum(node.right, curr_sum - node.val)`\n```Python\ndef hasPathSum(self, root: TreeNode, sum: int) -> bool:\n\tif not root:\n\t\treturn False\n\tif not root.left and not root.right and root.val == sum:\n\t\treturn True\n\treturn self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)\n```\n\n#### II. DFS iterative solution\nAlgorithm:\n1. Create empty stack and push root node and current sum to stack.\n2. Do followind steps while stack is not empty:\n\t * Pop `(node, curr_sum)` from stack\n\t * Cheack that node is leaf and `node.val == sum`. If it\'s true - return True, else go to the next step\n\t * Push left child of popped node and current sum decreased by popped node value `(node.left, curr_sum - node.val)`.\n\t * Push right child of popped node and current sum decreased by popped node value `(node.right, curr_sum - node.val)`.\n3. Return False if sum is not found.\n```Python\ndef hasPathSum(self, root: TreeNode, sum: int) -> bool:\n\tstack = [(root, sum)]\n\twhile stack:\n\t\tnode, curr_sum = stack.pop()\n\tif not node:\n\t\tcontinue\n\tif not node.left and not node.right and curr_sum == node.val:\n\t\treturn True\n\tstack.append((node.left, curr_sum - node.val))\n\tstack.append((node.right, curr_sum - node.val))\n\treturn False\n```\n\n#### III. BFS Solution\n\nAlgorithm:\n1. Create empty deque (double-ended queue) and push root node and current sum to queue.\n2. Do followind steps while queue is not empty:\n\t * Do popfront/popleft `(node, curr_sum)` from queue\n\t * If node is None - continue\n\t * Cheack that node is leaf and `node.val == sum`. If it\'s true - return True, else go to the next step\n\t * Push left child of popped node and current sum decreased by popped node value `(node.left, curr_sum - node.val)` to the queue.\n\t * Push right child of popped node and current sum decreased by popped node value `(node.right, curr_sum - node.val)` to the queue.\n3. Return False if sum is not found.\n\n```Python\nfrom collections import deque\n\ndef hasPathSum(self, root: TreeNode, sum: int) -> bool:\n\tdeq = deque()\n\tdeq.append((root, sum))\n\t\twhile deq:\n\t\t\tnode, curr_sum = deq.popleft()\n\t\t\tif not node:\n\t\t\t\tcontinue\n\t\t\tif not node.left and not node.right and curr_sum == node.val:\n\t\t\t\treturn True\n\t\t\tdeq.append((node.left, curr_sum - node.val))\n\t\t\tdeq.append((node.right, curr_sum - node.val))\n\treturn False\n``` | 50 | 0 | ['Depth-First Search', 'Breadth-First Search', 'Python3'] | 1 |
path-sum | 【Video】Using DFS. | video-using-dfs-by-niits-psag | IntuitionUsing DFS.Solution Video⭐️⭐️ Don't forget to subscribe to my channel! ⭐️⭐️■ Subscribe URL
http://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_c | niits | NORMAL | 2025-02-17T17:18:10.766084+00:00 | 2025-02-18T16:02:47.096493+00:00 | 4,807 | false | # Intuition
Using DFS.
---
# Solution Video
https://youtu.be/pAZ3HqA7awU
### ⭐️⭐️ Don't forget to subscribe to my channel! ⭐️⭐️
**■ Subscribe URL**
http://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1
Subscribers: 14,550
Thank you for your support!
---
# Approach

The description says "return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum."
That's why we should sue DFS for this question.
We will find leaf nodes. Question is how can we find leaf nodes?
---
⭐️ Points
Condition to find leaf nodes is
**root.left is null and root.right is null**
---
Until we find one of leaf nodes, **we will subtract node value we find from targetSum** so that we will be able to make sure the current path is `true` case or `false` case.
Let's see one by one.
```
targetSum = 22
```
We start from root node. That is not one of leaf nodes, so just subtract the value from `targetSum`.
```
targetSum = 22 - 5 = 17
```
Let's move left side first. The next value is `4` and that is not one of leaf nodes.
```
targetSum = 17 - 4 = 13
```
Next, we find `11`.
```
targetSum = 13 - 11 = 2
```
Next we find `7`. That is one of leaf nodes.
```
targetSum = 2 - 7 = -5
```
Now `targetSum` is `-5` which is false case, **because if it's true case, `targetSum` should be `0` at one of leaf nodes.**
Let's go back to `11`. We change direction. That means we go right. Current `targetSum` should be `2`. And we find `2`.
```
targetSum = 2 - 2 = 0
```
```
return true
```
# Complexity
Based on Python. Other might be different.
- Time complexity: $$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(n)$$
If the input is a skewed tree.
```python []
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
if not root.left and not root.right:
return targetSum - root.val == 0
targetSum -= root.val
return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum)
```
```javascript []
var hasPathSum = function(root, targetSum) {
if (!root) return false;
if (!root.left && !root.right) {
return targetSum - root.val === 0;
}
targetSum -= root.val;
return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);
};
```
```java []
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
if (root.left == null && root.right == null) {
return targetSum - root.val == 0;
}
targetSum -= root.val;
return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);
}
}
```
```C++ []
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) return false;
if (!root->left && !root->right) {
return targetSum - root->val == 0;
}
targetSum -= root->val;
return hasPathSum(root->left, targetSum) || hasPathSum(root->right, targetSum);
}
};
```
# Step by Step Algorithm
### **Step 1: Base Case - Check if the Tree is Empty**
#### **Code:**
```python
if not root:
return False
```
#### **Explanation:**
- If `root` is `None` (i.e., the tree is empty or we reach a null node in recursion), return `False`.
- This means there is no path available to check.
---
### **Step 2: Check if the Current Node is a Leaf Node**
#### **Code:**
```python
if not root.left and not root.right:
return targetSum - root.val == 0
```
#### **Explanation:**
- If the current node **does not** have left or right children, it is a **leaf node**.
- Check if `targetSum - root.val == 0` (i.e., whether the remaining sum after subtracting `root.val` equals zero).
- If `True`, return `True` because a valid path is found; otherwise, return `False`.
---
### **Step 3: Update the Target Sum**
#### **Code:**
```python
targetSum -= root.val
```
#### **Explanation:**
- Subtract the current node's value from `targetSum`.
- This reduces the problem to checking whether there exists a path in the left or right subtree with the updated `targetSum`.
---
### **Step 4: Recursive Calls to Left and Right Subtrees**
#### **Code:**
```python
return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum)
```
#### **Explanation:**
- Recursively call `hasPathSum` on the **left** and **right** children with the updated `targetSum`.
- If **either** the left or right subtree has a valid path, return `True` (using the `or` operator).
- If neither subtree contains a valid path, return `False`.
---
Thank you for reading my post.
⭐️ Please upvote it and don't forget to subscribe to my channel!
⭐️ Subscribe URL
http://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1
⭐️ related video
https://youtu.be/oz4JacPG-8E
| 44 | 0 | ['Tree', 'Depth-First Search', 'Binary Tree', 'C++', 'Java', 'Python3', 'JavaScript'] | 0 |
path-sum | Easy, 5 Lines and Clean Java Solution | easy-5-lines-and-clean-java-solution-by-exb7h | You simply check if current node (starting with root) is a leaf node and sum is equal its value. If not, you just check left or right with the decremented sum. | berkayk | NORMAL | 2016-03-05T20:40:54+00:00 | 2016-03-05T20:40:54+00:00 | 6,883 | false | You simply check if current node (starting with root) is a leaf node and sum is equal its value. If not, you just check left or right with the decremented sum. If one of them returns true, it has a path.\n\n public boolean hasPathSum(TreeNode root, int sum) { \n if (root == null)\n return false;\n \n if (root.left == null && root.right == null && root.val == sum) // Leaf check\n return true;\n \n return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);\n } | 42 | 0 | ['Java'] | 5 |
path-sum | A Java Concise solution | a-java-concise-solution-by-mostafa2-dkhk | public boolean hasPathSum(TreeNode root, int sum) {\n if(root == null){\n\t return false;\n\t }\n if(root.left == null && root.right == null){ | mostafa2 | NORMAL | 2015-06-06T15:01:28+00:00 | 2015-06-06T15:01:28+00:00 | 11,910 | false | public boolean hasPathSum(TreeNode root, int sum) {\n if(root == null){\n\t return false;\n\t }\n if(root.left == null && root.right == null){\n\t return (root.val == sum);\n\t }\n\t return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);\n \t \n } | 40 | 0 | [] | 5 |
path-sum | ✅ 🔥 0 ms Runtime Beats 100% User🔥|| Code Idea ✅ || Algorithm & Solving Step ✅ || | 0-ms-runtime-beats-100-user-code-idea-al-cdb6 | \n\n\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n### Intuition :\nThe problem requires checking if there is a root-to-leaf path in a | Letssoumen | NORMAL | 2024-12-04T00:12:57.040857+00:00 | 2024-12-04T00:12:57.040893+00:00 | 5,717 | false | \n\n\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n### **Intuition** :\nThe problem requires checking if there is a **root-to-leaf path** in a binary tree whose nodes sum up to a given `targetSum`. A **leaf node** is defined as a node with no children. We can solve this problem using **Depth-First Search (DFS)** or **Breadth-First Search (BFS)**.\n\n### **Approach** :\n1. **Depth-First Search (DFS) Recursive**:\n - Traverse the tree in a depth-first manner.\n - At each node, subtract its value from the current `targetSum`.\n - If you reach a leaf node and the remaining `targetSum` becomes zero, return `True`.\n - If no valid path is found, return `False`.\n\n2. **Breadth-First Search (BFS) Iterative**:\n - Use a queue to traverse the tree level by level.\n - Keep track of the cumulative sum along the path.\n - If a leaf node is reached and its cumulative sum equals `targetSum`, return `True`.\n - If all nodes are processed and no valid path is found, return `False`.\n\n---\n\n### **Algorithm**. :\n \n#### **DFS Recursive** :\n1. If the tree is empty (`root == None`), return `False`.\n2. Subtract the current node\u2019s value from the `targetSum`.\n3. If the node is a leaf and the remaining `targetSum` equals `0`, return `True`.\n4. Recursively call the function for left and right subtrees.\n5. Return `True` if either subtree returns `True`.\n\n#### **DFS Code (Python, C++, Java)** : (comments are added for easy to understand )\n\n---\n\n### **Python Solution (DFS)** :\n\n```python\nclass Solution:\n def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:\n if not root:\n return False\n \n # Subtract current node\'s value from targetSum\n targetSum -= root.val\n \n # Check if it\'s a leaf node and targetSum becomes zero\n if not root.left and not root.right:\n return targetSum == 0\n \n # Recursively check left and right subtrees\n return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum)\n```\n\n---\n\n### **C++ Solution (DFS)** :\n\n```cpp\n#include <iostream>\nusing namespace std;\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int targetSum) {\n if (!root) return false;\n \n targetSum -= root->val;\n \n if (!root->left && !root->right) {\n return targetSum == 0;\n }\n \n return hasPathSum(root->left, targetSum) || hasPathSum(root->right, targetSum);\n }\n};\n```\n\n---\n\n### **Java Solution (DFS)** :\n\n```java\nclass Solution {\n public boolean hasPathSum(TreeNode root, int targetSum) {\n if (root == null) return false;\n \n targetSum -= root.val;\n \n if (root.left == null && root.right == null) {\n return targetSum == 0;\n }\n \n return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);\n }\n}\n```\n\n---\n\n### **Time Complexity** :\n- **DFS**: O(n), where n is the number of nodes in the tree. Each node is visited once.\n- **Space Complexity**: \n - O(h), where h is the height of the tree for recursive call stack in DFS. \n - In the worst case, h = O(n) for a skewed tree, and O(log n) for a balanced tree.\n\n---\n\n### **Alternative Approach: BFS** :\n\n#### **Python BFS Solution** :\n\n```python\nfrom collections import deque\n\nclass Solution:\n def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:\n if not root:\n return False\n \n queue = deque([(root, targetSum - root.val)])\n \n while queue:\n node, curr_sum = queue.popleft()\n \n # Check if the current node is a leaf and its sum is zero\n if not node.left and not node.right and curr_sum == 0:\n return True\n \n # Add left child to queue if exists\n if node.left:\n queue.append((node.left, curr_sum - node.left.val))\n \n # Add right child to queue if exists\n if node.right:\n queue.append((node.right, curr_sum - node.right.val))\n \n return False\n```\n\n### **Advantages of BFS** :\n- If the tree is wide and shallow, BFS may find the result earlier than DFS.\n\n\n\n | 39 | 0 | ['Tree', 'Depth-First Search', 'Breadth-First Search', 'Binary Tree', 'C++', 'Java', 'Python3'] | 0 |
path-sum | C++ || Efficient|| Recursive|| Easy || 3 lines || Solution ||with comments || | c-efficient-recursive-easy-3-lines-solut-e48l | If you understand the approach please please upvote!!!\nThanks :)\n```\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int targetSum) {\n | Debajyoti-Shit | NORMAL | 2022-02-06T06:04:56.144751+00:00 | 2022-02-06T06:04:56.144795+00:00 | 2,828 | false | #### If you understand the approach please please upvote!!!\n***Thanks :)***\n```\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int targetSum) {\n if(root==NULL) return false;\n \n //we reached here,i.e the root is not NULL, so we took the root value in our sum, and remaining targetSum is targetSum-root value.\n targetSum=targetSum-root->val;\n \n //if the current node is a leaf and its value is equal to the sum, we\'ve found a path\n if(targetSum==0 && root->left==NULL && root->right==NULL) return true;\n \n // recursively call to traverse the left and right sub-tree\n // return true if any of the two recursive call return true\n return hasPathSum(root->left,targetSum) || hasPathSum(root->right,targetSum);\n }\n};\n | 39 | 1 | ['Depth-First Search', 'Breadth-First Search', 'Recursion', 'C', 'C++'] | 1 |
path-sum | Java ||Three Easy Approach With Explanation || Preorder || Postorder || 0ms | java-three-easy-approach-with-explanatio-5j4o | \n1 st Approach \nclass Solution\n{\n public boolean hasPathSum(TreeNode root, int targetSum)//we always try to approach the zero ----0++++ from any half lef | swapnilGhosh | NORMAL | 2021-07-10T17:20:00.799065+00:00 | 2022-01-02T19:07:18.353304+00:00 | 2,282 | false | ```\n1 st Approach \nclass Solution\n{\n public boolean hasPathSum(TreeNode root, int targetSum)//we always try to approach the zero ----0++++ from any half left or right, like taking limit//if zero found at leaf then true else false\n {\n if(root == null)\n return false;//base case when the selected path is not the desired path //we return false and check in next half of the subtree//base case for terminnation of the recursion \n else if(root.left == null && root.right == null && targetSum - root.val == 0)//we have faith in tree that it can find the node if present where the value nutralizes each other at 0\n return true;//only the case when we are returning true \n else\n return hasPathSum(root.left,targetSum - root.val)||hasPathSum(root.right,targetSum - root.val);//if present in left is good otherwiswe we are searching in right subtree recursively //all permutation in ways are done by recursion and not our tension \n }\n}//Please do Upvote, It helps a lot\n```\n```\n2 nd Approach \n\nclass Solution \n{\n private boolean flag= false;//we are taking the base case as false, if the sum is not found and if the target sum lies in the path from root to leaf, we make the flag true \n \n public boolean hasPathSum(TreeNode root, int targetSum) \n {\n int sum = 0;//calculate the downward sum \n \n Helper(root, sum, targetSum);//it helps us calculate the sum of each node for each path from root to leaf and tells us that our desired sum is present or not, by adding the node at that path \n \n return flag;//returns true if sum is present else false is returned \n }\n public TreeNode Helper(TreeNode root, int sum, int targetSum)\n {//postorder traversal + semi preorder traversal(accesing root beforehand once), we want to know about child first and then the parent \n if(root == null)//base case when we hit the null node, to tell the parent no node is present we return null \n return null;\n //ROOT\n sum= sum + root.val;//adding the node value to sum at each level//accesing root beforehand once\n \n TreeNode left= Helper(root.left, sum, targetSum);//recursing down the left subtree and knowing about the left child//storring the reference to detect it is leaf or not, if it is leaf then left == null//LEFT\n TreeNode right= Helper(root.right, sum, targetSum);//recursing down the right subtree and knowing about the right child//storring the reference to detect it is leaf or not, if it is leaf then right == null//RIGHT\n \n //ROOT\n if(sum == targetSum && left == null && right == null) //if we reached to our desired sum and the parent node is a leaf node, we got our path finally \n flag= true;//we make the flag to true as the desired path from root to leaf is achived \n \n return root;//returning root, to tell the parent that I am present \n }\n}\n```\n```\n3 rd Approach \nclass Solution {\n //0 -- null node, 1 means node, 2 found path node //metadata about the current status of the node \n public int PathSum(TreeNode root, int curr, int targetSum){\n if ( root == null){\n return 0;//we return 0 to tell that i am leaf \n }\n curr+= root.val;//preorder sum\n \n int left= PathSum(root.left, curr, targetSum);\n \n if ( left == 2 )\n return 2;//if left path conatins the desired path to leaf node with target sum, we no need to go to right part reccursively\n \n int right= PathSum(root.right, curr, targetSum);\n \n if ( right == 2)\n return 2;//if right path conatins the desired path to leaf node with target sum, we no need to check further condition we just return 2 in order to indicate desired path has been found\n \n //Backtracking postorder traversal \n \n if ( left == 0 && right == 0 && targetSum == curr){//if we reach to leaf node with desired sum we return 2, inorder to indicate we have found the path \n return 2;\n }\n \n return 1;//we return 1, to tell that we have not found the desired path till now \n }\n public boolean hasPathSum(TreeNode root, int targetSum) {\n if ( root == null){\n return false;//empty graph, no path tp find we return false \n }\n \n if ( PathSum(root, 0, targetSum) == 2)//found path case \n return true;\n else\n return false;//not path found case \n }\n}\n``` | 36 | 0 | ['Depth-First Search', 'Recursion', 'Java'] | 4 |
path-sum | ✅Accepted| | ✅Easy solution || ✅Short & Simple || ✅Best Method | accepted-easy-solution-short-simple-best-u0da | \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( | sanjaydwk8 | NORMAL | 2023-01-15T12:02:14.745915+00:00 | 2023-01-15T12:02:14.745952+00:00 | 5,117 | false | \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 bool hasPathSum(TreeNode* root, int targetSum) {\n if(!root)\n return false;\n if(!root->left && !root->right && root->val==targetSum)\n return true;\n else\n return hasPathSum(root->left, targetSum-root->val) ||\n hasPathSum(root->right, targetSum-root->val);\n }\n};\n```\nPlease **UPVOTE** if it helps \u2764\uFE0F\uD83D\uDE0A\nThank You and Happy To Help You!! | 31 | 0 | ['C++'] | 1 |
path-sum | My Python iterative DFS solution | my-python-iterative-dfs-solution-by-clue-qsz8 | \n def hasPathSum(self, root, sum):\n if root is None:\n return False\n stack = [(root, sum)]\n while stack:\n nod | clue | NORMAL | 2014-11-17T01:58:23+00:00 | 2014-11-17T01:58:23+00:00 | 6,517 | false | \n def hasPathSum(self, root, sum):\n if root is None:\n return False\n stack = [(root, sum)]\n while stack:\n node, _sum = stack.pop()\n if node.left is node.right is None and node.val == _sum:\n return True\n if node.left:\n stack.append((node.left, _sum - node.val))\n if node.right:\n stack.append((node.right, _sum - node.val))\n return False\n\n\nCurrent node and the sum until current node as a tuple is pushed onto the stack to keep track of the sum. | 29 | 0 | ['Python'] | 5 |
path-sum | [C++] 97% Runtime Iterative and Recursive Solution | c-97-runtime-iterative-and-recursive-sol-pnft | Iterative Solution \n\nbool hasPathSum(TreeNode* root, int sum) {\n if(root == NULL) return false;\n stack<pair<TreeNode*,int>> stack;\n st | hunarbatra | NORMAL | 2020-02-23T19:37:09.726500+00:00 | 2020-02-23T19:37:09.726541+00:00 | 2,924 | false | Iterative Solution \n```\nbool hasPathSum(TreeNode* root, int sum) {\n if(root == NULL) return false;\n stack<pair<TreeNode*,int>> stack;\n stack.push({root, root->val});\n while(!stack.empty()) {\n TreeNode* current = stack.top().first; \n int total_sum = stack.top().second; stack.pop();\n if(current->right) stack.push({current->right, total_sum+current->right->val});\n if(current->left) stack.push({current->left, total_sum+current->left->val});\n if(!current->right && !current->left && total_sum==sum) { //if its a leaf\n return true; //and total sum is found\n }\n }\n return false;\n }\n```\n\nRecursive Solution\n```\nbool hasPathSum(TreeNode* root, int sum) {\n if(root == NULL) return false;\n int new_sum = sum - root->val;\n if(!root->left && !root->right) return new_sum==0;\n return hasPathSum(root->left, new_sum) || hasPathSum(root->right, new_sum);\n }\n``` | 25 | 0 | ['Recursion', 'C', 'Iterator', 'C++'] | 2 |
path-sum | Python Elegant & Short | DFS | python-elegant-short-dfs-by-kyrylo-ktl-5seh | \nclass Solution:\n """\n Time: O(n)\n Memory: O(n)\n """\n\n def hasPathSum(self, root: Optional[TreeNode], target: int) -> bool:\n if | Kyrylo-Ktl | NORMAL | 2022-10-04T07:17:55.317103+00:00 | 2022-10-04T07:17:55.317142+00:00 | 2,483 | false | ```\nclass Solution:\n """\n Time: O(n)\n Memory: O(n)\n """\n\n def hasPathSum(self, root: Optional[TreeNode], target: int) -> bool:\n if root is None:\n return False\n if root.left is None and root.right is None:\n return target == root.val\n return self.hasPathSum( root.left, target - root.val) or \\\n self.hasPathSum(root.right, target - root.val)\n```\n\nIf you like this solution remember to **upvote it** to let me know.\n | 24 | 0 | ['Depth-First Search', 'Python', 'Python3'] | 0 |
path-sum | Python solution | python-solution-by-zitaowang-2fa0 | Recursion:\n\nclass Solution(object):\n def hasPathSum(self, root, sum):\n """\n :type root: TreeNode\n :type sum: int\n :rtype: | zitaowang | NORMAL | 2018-09-14T03:12:50.114055+00:00 | 2018-10-01T23:40:49.345775+00:00 | 3,333 | false | Recursion:\n```\nclass Solution(object):\n def hasPathSum(self, root, sum):\n """\n :type root: TreeNode\n :type sum: int\n :rtype: bool\n """\n if not root:\n return False\n elif not root.left and not root.right:\n if root.val == sum:\n return True\n else:\n return False\n return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)\n```\nDFS:\n```\nclass Solution(object):\n def hasPathSum(self, root, sum):\n """\n :type root: TreeNode\n :type sum: int\n :rtype: bool\n """\n if not root:\n return False\n stack = [(root,sum - root.val)]\n while stack:\n u = stack.pop()\n if not u[0].left and not u[0].right:\n if u[1] == 0:\n return True\n if u[0].left:\n stack.append((u[0].left, u[1]-u[0].left.val))\n if u[0].right:\n stack.append((u[0].right, u[1]-u[0].right.val))\n return False\n``` | 23 | 1 | [] | 4 |
path-sum | 🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line | leetcode-the-hard-way-explained-line-by-6yw6b | Please check out LeetCode The Hard Way for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full li | __wkw__ | NORMAL | 2022-10-04T03:40:39.029283+00:00 | 2022-10-04T03:40:39.029350+00:00 | 1,666 | false | Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post.\n\n---\n\n<iframe src="https://leetcode.com/playground/PNj2PJfY/shared" frameBorder="0" width="100%" height="500"></iframe> | 21 | 1 | ['Recursion', 'C', 'C++'] | 7 |
path-sum | 3-line Java Solution | 3-line-java-solution-by-dummyshooter-lq4r | \n public boolean hasPathSum(TreeNode root, int sum) {\n if (root == null) return false;\n if (root.left == null && root.right == null && root. | dummyshooter | NORMAL | 2016-04-08T15:19:46+00:00 | 2016-04-08T15:19:46+00:00 | 2,324 | false | \n public boolean hasPathSum(TreeNode root, int sum) {\n if (root == null) return false;\n if (root.left == null && root.right == null && root.val == sum) return true;\n return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);\n } | 20 | 0 | ['Recursion', 'Java'] | 0 |
path-sum | JAVASCRIPT || EASY CODE || THUMBS UP IF YOU LIKE ❤️ | javascript-easy-code-thumbs-up-if-you-li-2oz5 | \n# Code\n\n\nvar hasPathSum = function (root, targetSum) {\n if (!root)\n return false\n if (root.val === targetSum && (!root.left && !root.right) | sikkasakshi2 | NORMAL | 2022-12-11T19:20:51.534075+00:00 | 2022-12-11T19:20:51.534114+00:00 | 1,835 | false | \n# Code\n```\n\nvar hasPathSum = function (root, targetSum) {\n if (!root)\n return false\n if (root.val === targetSum && (!root.left && !root.right))\n return true\n\n return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val)\n\n};\n``` | 18 | 0 | ['JavaScript'] | 5 |
path-sum | C++ DFS - Multiple Solutions | c-dfs-multiple-solutions-by-aishvaryarat-5nx2 | \nSolution 1: \nclass Solution {\npublic:\n \n int pathSum = 0; \n bool pathFound = false;\n \n bool hasPathSum(TreeNode* root, int targetSum) \n | aishvaryarathore | NORMAL | 2021-06-06T20:20:11.842329+00:00 | 2021-07-07T23:21:39.990307+00:00 | 1,449 | false | ```\nSolution 1: \nclass Solution {\npublic:\n \n int pathSum = 0; \n bool pathFound = false;\n \n bool hasPathSum(TreeNode* root, int targetSum) \n { \n if(root != NULL)\n {\n pathSum += root->val;\n \n if(root->left == NULL && root->right == NULL)\n {\n if(pathSum == targetSum)\n pathFound = true;\n }\n else\n {\n hasPathSum(root->left, targetSum);\n hasPathSum(root->right, targetSum);\n }\n \n pathSum -= root->val; \n }\n\n return (pathFound == true) ? true : false;\n }\n};\n\nSolution 2: \n\nclass Solution {\npublic:\n \n \n bool hasPathSum(TreeNode* root, int targetSum) \n { \n if (root == nullptr) \n {\n return false;\n }\n\n // if the current node is a leaf and its value is equal to the sum, we\'ve found a path\n if (root->val == targetSum && root->left == nullptr && root->right == nullptr) \n {\n return true;\n }\n\t\t\n // recursively call to traverse the left and right sub-tree\n // return true if any of the two recursive call return true\n return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val);\n }\n};\n\n``` | 18 | 0 | ['Depth-First Search', 'C'] | 3 |
path-sum | \u3010Python\u3011Recursive solution with explanation and thinking process | u3010pythonu3011recursive-solution-with-p8gie | Base case\n1. This question wants to find a path from node to the leaf, so the node who satisfies must be a leaf (not node.left and not nood.right)\n2. I want t | xiaohk | NORMAL | 2016-06-09T15:36:09+00:00 | 2016-06-09T15:36:09+00:00 | 1,551 | false | ## Base case\n1. This question wants to find a path from node to the **leaf**, so the node who satisfies must be a **leaf** (`not node.left and not nood.right`)\n2. I want to recursively subtract the `sum` by current node's value, so the leaf node of correct path must have the same value of its assigned `sum`\n\n## Recursive step\n1. We want to traverse all the nodes, so `node.left` and `node.right` must be called parallelly\n2. One valid path is enough, so we want to use `or` to connect two "branches"\n3. Considering each node as the root of its children, `sum` should be modified from its parent\n\n<br>\n\n def hasPathSum(self, root, sum):\n if not root:\n return False\n \n if root.val == sum and not root.left and not root.right:\n return True\n \n return self.hasPathSum(root.left, sum - root.val) or \\\n self.hasPathSum(root.right, sum - root.val) | 18 | 0 | ['Python'] | 1 |
path-sum | Very Easy || 100% || 3 Line || Explained (Java, C++, Python, JS, C, Python3) | very-easy-100-3-line-explained-java-c-py-ytj1 | Java Solution:\nRuntime: 0 ms, faster than 100.00% of Java online submissions for Path Sum.\n\nclass Solution {\n public boolean hasPathSum(TreeNode root, in | PratikSen07 | NORMAL | 2022-08-16T07:03:31.701021+00:00 | 2022-08-16T12:16:56.958267+00:00 | 3,151 | false | # **Java Solution:**\nRuntime: 0 ms, faster than 100.00% of Java online submissions for Path Sum.\n```\nclass Solution {\n public boolean hasPathSum(TreeNode root, int targetSum) {\n // If the tree is empty i.e. root is NULL, return false...\n\t if (root == null) return false;\n // If there is only a single root node and the value of root node is equal to the targetSum...\n\t if (root.val == targetSum && (root.left == null && root.right == null)) return true;\n // Call the same function recursively for left and right subtree...\n\t return hasPathSum(root.left, targetSum - root.val)|| hasPathSum(root.right, targetSum - root.val);\n }\n}\n```\n\n# **C++ Solution:**\nRuntime: 6 ms, faster than 89.18% of C++ online submissions for Path Sum.\nMemory Usage: 11.2 MB, less than 92.17% of C++ online submissions for Path Sum.\n```\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int targetSum) {\n // If the tree is empty i.e. root is NULL, return false...\n\t if (root == NULL) return false;\n // If there is only a single root node and the value of root node is equal to the targetSum...\n\t if (root->val == targetSum && (root->left == NULL && root->right == NULL)) return true;\n // Call the same function recursively for left and right subtree...\n\t return hasPathSum(root->left, targetSum - root->val)|| hasPathSum(root->right, targetSum - root->val);\n }\n};\n```\n\n\n# **Python Solution:**\n```\nclass Solution(object):\n def hasPathSum(self, root, targetSum):\n # If the tree is empty i.e. root is NULL, return false...\n\t if root is None: return 0\n # If there is only a single root node and the value of root node is equal to the targetSum...\n\t if root.val == targetSum and (root.left is None and root.right is None): return 1\n # Call the same function recursively for left and right subtree...\n\t return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)\n```\n \n# **JavaScript Solution:**\n```\nvar hasPathSum = function(root, targetSum) {\n // If the tree is empty i.e. root is NULL, return false...\n\tif (root == null) return false;\n // If there is only a single root node and the value of root node is equal to the targetSum...\n\tif (root.val == targetSum && (root.left == null && root.right == null)) return true;\n // Call the same function recursively for left and right subtree...\n\treturn hasPathSum(root.left, targetSum - root.val)|| hasPathSum(root.right, targetSum - root.val);\n};\n```\n\n# **C Language:**\n```\nbool hasPathSum(struct TreeNode* root, int targetSum){\n // If the tree is empty i.e. root is NULL, return false...\n\tif (root == NULL) return false;\n // If there is only a single root node and the value of root node is equal to the targetSum...\n\tif (root->val == targetSum && (root->left == NULL && root->right == NULL)) return true;\n // Call the same function recursively for left and right subtree...\n\treturn hasPathSum(root->left, targetSum - root->val)|| hasPathSum(root->right, targetSum - root->val);\n}\n```\n\n# **Python3 Solution:**\n```\nclass Solution:\n def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n # If the tree is empty i.e. root is NULL, return false...\n\t if root is None: return 0\n # If there is only a single root node and the value of root node is equal to the targetSum...\n\t if root.val == targetSum and (root.left is None and root.right is None): return 1\n # Call the same function recursively for left and right subtree...\n\t return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)\n```\n**I am working hard for you guys...\nPlease upvote if you found any help with this code...** | 17 | 0 | ['Recursion', 'C', 'Python', 'Java', 'Python3', 'JavaScript'] | 2 |
path-sum | 🌺C#, Java, Python3, JavaScript Solution - O(n) | c-java-python3-javascript-solution-on-by-lu2s | Here to see the full explanation :\u2B50Zyrastory - #112 Path Sum\u2B50\n\n\n---\n\nWe can use a simple recursive approach and leverage DFS to traverse a binary | Daisy001 | NORMAL | 2023-10-09T01:08:11.486304+00:00 | 2023-10-09T01:11:22.491596+00:00 | 2,173 | false | **Here to see the full explanation :\u2B50[Zyrastory - #112 Path Sum](https://zyrastory.com/en/coding-en/leetcode-en/leetcode-112-path-sum-solution-and-explanation-en/)\u2B50**\n\n\n---\n\nWe can use a simple recursive approach and leverage DFS to traverse a binary tree.\n\nThis algorithm is quite efficient because it doesn\'t need to enumerate all possible paths but instead calculates the path sum during traversal. Once it finds a path that matches the target sum, it can return immediately.\n\n# Example :\n# C#\nSolution\n```\npublic class Solution {\n public bool HasPathSum(TreeNode root, int targetSum) {\n if (root == null) {\n return false;\n }\n\n //minus value of current node\n targetSum -= root.val;\n \n //check if now a leaf node\n if (root.left == null && root.right == null) {\n return targetSum == 0;\n }\n\n return HasPathSum(root.left, targetSum) || HasPathSum(root.right, targetSum);\n }\n}\n```\n\n---\n\n# Java\n```\nclass Solution {\n public boolean hasPathSum(TreeNode root, int targetSum) {\n if (root == null) {\n return false;\n }\n\n //minus value of current node\n targetSum -= root.val;\n \n //check if now a leaf node\n if (root.left == null && root.right == null) {\n return targetSum == 0;\n }\n\n return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);\n }\n}\n```\n\n---\n# Python3\n```\nclass Solution:\n def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n if(root==None):\n return False\n \n #minus value of current node\n targetSum = targetSum-root.val\n \n #check if now a leaf node\n if (root.left == None and root.right == None):\n return targetSum == 0\n \n return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum)\n```\n\n---\n\n# JavaScript\n```\nvar hasPathSum = function(root, targetSum) {\n if (root == null) {\n return false;\n }\n\n //minus value of current node\n targetSum -= root.val;\n \n //check if now a leaf node\n if (root.left == null && root.right == null) {\n return targetSum == 0;\n }\n\n return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);\n};\n```\n\n\n**If you got any problem about the explanation or you need other programming language solution, please feel free to let me know (leave comment or messenger me).**\n\nThank you\uD83C\uDF3A! | 16 | 0 | ['Java', 'Python3', 'JavaScript', 'C#'] | 0 |
path-sum | Path Sum with step by step explanation | path-sum-with-step-by-step-explanation-b-u1jj | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nThis solution uses an iterative approach with a stack to traverse the bin | Marlen09 | NORMAL | 2023-02-16T12:07:12.684425+00:00 | 2023-02-16T12:07:12.684463+00:00 | 3,310 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThis solution uses an iterative approach with a stack to traverse the binary tree and keep track of the current path value. It checks if the current node is a leaf node and its value matches the target sum. If not, it adds the left and right children to the stack along with their updated path value. It returns False if no such path is found.\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```\nclass Solution:\n def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n if not root:\n return False\n \n # Use a list to store the path from root to the current node\n stack = [(root, root.val)]\n \n while stack:\n node, val = stack.pop()\n \n # Check if the current node is a leaf node and its value matches the targetSum\n if not node.left and not node.right and val == targetSum:\n return True\n \n # Add the left and right children to the stack along with their updated path value\n if node.left:\n stack.append((node.left, val + node.left.val))\n if node.right:\n stack.append((node.right, val + node.right.val))\n \n return False\n\n``` | 16 | 0 | ['Tree', 'Depth-First Search', 'Breadth-First Search', 'Python', 'Python3'] | 0 |
path-sum | JAVA || Easy Solution || 2 Liner Code.|| Recursive | java-easy-solution-2-liner-code-recursiv-bisx | \tPLEASE UPVOTE IF YOU LIKE.\n\npublic class Solution {\n public boolean hasPathSum(TreeNode root, int sum) {\n if(root==null)return false;\n s | shivrastogi | NORMAL | 2022-10-04T04:42:56.189162+00:00 | 2022-10-04T04:42:56.189201+00:00 | 1,354 | false | \tPLEASE UPVOTE IF YOU LIKE.\n```\npublic class Solution {\n public boolean hasPathSum(TreeNode root, int sum) {\n if(root==null)return false;\n sum = sum - root.val;\n if(root.left==null && root.right==null){\n if(sum == 0)return true;\n else return false;\n }\n return hasPathSum(root.left,sum) || hasPathSum(root.right,sum);\n \n \n }\n \n \n}\n``` | 16 | 0 | ['Recursion', 'Java'] | 3 |
path-sum | ✔️ 100% Fastest Swift Solution | 100-fastest-swift-solution-by-sergeylesc-ykna | \n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * public var val: Int\n * public var left: TreeNode?\n * public var right | sergeyleschev | NORMAL | 2022-04-09T06:03:14.938261+00:00 | 2022-04-09T06:03:14.938295+00:00 | 838 | false | ```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * public var val: Int\n * public var left: TreeNode?\n * public var right: TreeNode?\n * public init() { self.val = 0; self.left = nil; self.right = nil; }\n * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }\n * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {\n * self.val = val\n * self.left = left\n * self.right = right\n * }\n * }\n */\nclass Solution {\n func hasPathSum(_ root: TreeNode?, _ targetSum: Int) -> Bool {\n guard let root = root else { return false }\n \n if root.val == targetSum && root.left == nil && root.right == nil { return true }\n \n return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val)\n }\n \n}\n```\n\nLet me know in comments if you have any doubts. I will be happy to answer.\n\nPlease upvote if you found the solution useful. | 16 | 0 | ['Swift'] | 1 |
path-sum | [Python] simple DFS | python-simple-dfs-by-qsmy41-ssx9 | \ndef hasPathSum(self, root: TreeNode, sum: int) -> bool:\n if not root: # edge case\n return False\n if not root.left and not root.right: \n | qsmy41 | NORMAL | 2020-08-08T12:27:41.614222+00:00 | 2020-08-08T12:27:41.614255+00:00 | 1,745 | false | ```\ndef hasPathSum(self, root: TreeNode, sum: int) -> bool:\n if not root: # edge case\n return False\n if not root.left and not root.right: \n return sum == root.val\n return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)\n``` | 16 | 0 | ['Depth-First Search', 'Recursion', 'Python3'] | 2 |
path-sum | JAVA 100% FASTER SOLUTION🚀🚀 || STEP BY STEP EXPLAINED😉 | java-100-faster-solution-step-by-step-ex-4lvy | 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 | abhiyadav05 | NORMAL | 2023-07-15T11:36:20.173486+00:00 | 2023-07-15T11:37:33.674692+00:00 | 1,633 | 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)$$ -->O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(H)\n\n\n\n# Code\n```\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 boolean hasPathSum(TreeNode root, int targetSum) {\n if (root == null) {\n return false;\n }\n \n // Check if the current node is a leaf node and its value matches the targetSum\n if (root.left == null && root.right == null && root.val == targetSum) {\n return true;\n }\n \n // Recursively check the left and right subtrees with updated targetSum\n return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);\n }\n}\n``` | 15 | 0 | ['Tree', 'Binary Tree', 'Java'] | 2 |
path-sum | Path Sum || 99.22% FASTEST EXECUTION || C++ || 3 LINE EASY SOLUTION || SIMPLE AND SHORT | path-sum-9922-fastest-execution-c-3-line-xbhn | SHIVAM DAILY LEETCODE SOLUTIONS || CHECK : https://bit.ly/leetcode-solutions\nRuntime: 4 ms, faster than 99.22% of C++ online submissions for Path Sum.\nMemory | shivambit | NORMAL | 2022-10-04T05:51:40.536899+00:00 | 2022-10-04T05:51:40.536934+00:00 | 2,066 | false | **SHIVAM DAILY LEETCODE SOLUTIONS || CHECK : [https://bit.ly/leetcode-solutions](https://bit.ly/leetcode-solutions)\nRuntime: 4 ms, faster than 99.22% of C++ online submissions for Path Sum.\nMemory Usage: 21.4 MB, less than 38.76% of C++ online submissions for Path Sum.** \n\n```\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int sum)\n {\n if (!root) return false;\n if (!root->left && !root->right) return root->val == sum;\n return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);\n }\n};\n\n```\n\n | 15 | 1 | ['Recursion', 'C', 'C++'] | 4 |
path-sum | Easy JS Solution | easy-js-solution-by-hbjorbj-wg59 | \n/*\n1. Use DFS to try all possible paths.\n2. Keep track of the sum of path during traversal. When leaf node is reached, check if\nthe sum of path equals the | hbjorbj | NORMAL | 2021-05-14T01:02:40.862798+00:00 | 2021-05-14T01:05:23.141879+00:00 | 2,182 | false | ```\n/*\n1. Use DFS to try all possible paths.\n2. Keep track of the sum of path during traversal. When leaf node is reached, check if\nthe sum of path equals the target. If so, return true, else continue DFS traversal to\ntry other paths.\n*/\nvar hasPathSum = function(root, targetSum) {\n return dfs(root, targetSum);\n // T.C: O(N)\n // S.C: O(H)\n};\n\nconst dfs = (root, target) => {\n if (!root) {\n return false;\n }\n if (!root.left && !root.right) {\n return target - root.val === 0;\n }\n return dfs(root.left, target - root.val) || \n dfs(root.right, target - root.val);\n}\n``` | 14 | 0 | ['JavaScript'] | 1 |
path-sum | Python | Recursive approach | Easy to Solve | python-recursive-approach-easy-to-solve-p4uv7 | Think about one small tree. Let say we have only one node like\n\n\t\t\t\t\t 1\n\t\t\t\tNone None\n\nand targetSum is 1, so our condtion will be \n\n | vsahoo | NORMAL | 2021-05-04T06:38:30.046134+00:00 | 2021-05-05T05:33:57.542359+00:00 | 1,030 | false | Think about one small tree. Let say we have only one node like\n```\n\t\t\t\t\t 1\n\t\t\t\tNone None\n```\nand targetSum is 1, so our condtion will be \n```\nif root.left is None and root.right is None and root.val == targetSum:\n return True\n```\n \n 1\n\t\t\t\t2 3\nand targetSum is 4\nFor the above example we have the path sum in right hand side, so whenever we are recursively calling on a node we will check both side of the tree.\n```\n\nclass Solution:\n def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:\n \n if root is None: return False\n \n if root.left is None and root.right is None and root.val == targetSum:\n return True\n \n return self.hasPathSum(root.left, targetSum-root.val) or self.hasPathSum(root.right, targetSum-root.val)\n```\nPlease Upvote if you get it.\n\nPlease check out Path sum II solution. (https://leetcode.com/problems/path-sum-ii/discuss/1192146/Python-or-Recursive-approach-or-97-beats)\n | 14 | 0 | ['Recursion', 'Python'] | 2 |
path-sum | C++ Solution, recursion + Iterative-dfs + Iterative-bfs | c-solution-recursion-iterative-dfs-itera-4lhg | \nclass Solution {\n public:\n bool hasPathSum(TreeNode* root, int sum) {\n if (not root) return false;\n sum -= root->val;\n if (not root->left and n | saravanakumar_dharmaraj | NORMAL | 2020-07-19T16:46:37.225742+00:00 | 2020-07-19T21:31:12.449413+00:00 | 836 | false | ```\nclass Solution {\n public:\n bool hasPathSum(TreeNode* root, int sum) {\n if (not root) return false;\n sum -= root->val;\n if (not root->left and not root->right) {\n return sum == 0;\n }\n return hasPathSum(root->left, sum) || hasPathSum(root->right, sum);\n }\n};\n```\n//DFS\n```\nclass Solution {\n public:\n bool hasPathSum(TreeNode* root, int sum) {\n if (!root) return false;\n stack<pair<TreeNode*, int>> stk;\n stk.push({root, sum});\n while (!stk.empty()) {\n auto [node, curr_sum] = stk.top();\n stk.pop();\n curr_sum -= node->val;\n if (!node->left && !node->right && curr_sum == 0) {\n return true;\n }\n if (node->right) stk.push({node->right, curr_sum});\n if (node->left) stk.push({node->left, curr_sum});\n }\n return false;\n }\n};\n```\n// BFS\n```\nclass Solution {\n public:\n bool hasPathSum(TreeNode *root, int sum) {\n if (!root) return false;\n queue<pair<TreeNode *, int>> q;\n q.push({root, sum});\n while (!q.empty()) {\n auto [node, curr_sum] = q.front();\n q.pop();\n curr_sum -= node->val;\n if (!node->left && !node->right && curr_sum == 0) return true;\n if (node->left) q.push({node->left, curr_sum});\n if (node->right) q.push({node->right, curr_sum});\n }\n return false;\n }\n};\n\n\n``` | 14 | 0 | ['C'] | 0 |
path-sum | Video Solution | Intuition Explained | C++ | video-solution-intuition-explained-c-by-uahn0 | Video\nHey everyone, i have craeted a video solution for this problem where we discuss intuition for this problem, this video is part of my trees playlist and b | _code_concepts_ | NORMAL | 2024-07-24T09:48:26.429800+00:00 | 2024-07-27T09:45:19.716997+00:00 | 1,385 | false | # Video\nHey everyone, i have craeted a video solution for this problem where we discuss intuition for this problem, this video is part of my trees playlist and belongs to category "Root to leaf path".\n\nVideo link: https://youtu.be/6t-dWQSM-nw\nPlaylist link: https://www.youtube.com/playlist?list=PLICVjZ3X1Aca0TjUTcsD7mobU001CE7GL\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 bool hasPathSum(TreeNode* root, int targetSum) {\n if(!root){\n return false;\n }\n // if u are on leaf node\n if(!root->left && !root->right && targetSum -root->val==0){\n return true;\n }\n\n return hasPathSum(root->left, targetSum-root->val) || hasPathSum(root->right, targetSum-root->val);\n \n }\n};\n``` | 13 | 0 | ['C++'] | 0 |
path-sum | C++ solutions | c-solutions-by-infox_92-zf8o | \nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int sum) {\n if(!root)return false; //Terminatin | Infox_92 | NORMAL | 2022-11-10T06:34:42.707269+00:00 | 2022-11-10T06:34:42.707304+00:00 | 1,971 | false | ```\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int sum) {\n if(!root)return false; //Terminating Condition\n sum=sum-root->val; //Body\n if(sum==0&&!root->left&&!root->right)return true; //body\n return hasPathSum(root->left,sum)||hasPathSum(root->right,sum);//Propagation\n }\n};\n``` | 13 | 0 | ['C', 'C++'] | 0 |
path-sum | Share my 3 lines c++ solution | share-my-3-lines-c-solution-by-yhxdl-63n9 | /**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * | yhxdl | NORMAL | 2015-10-08T07:28:20+00:00 | 2015-10-08T07:28:20+00:00 | 2,387 | false | /**\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 */\n class Solution {\n public:\n bool hasPathSum(TreeNode* root, int sum) {\n if(!root) return false;\n if((root -> val == sum) && ((!root -> left) && (!root -> right))) return true;\n return hasPathSum(root -> left, sum - root -> val) || hasPathSum(root -> right, sum - root -> val);\n }\n }; | 13 | 1 | [] | 2 |
path-sum | solution | solution-by-mikhmanoff-oxzm | The function hasPathSum checks if there is a path from the root to the leaves in the binary tree defined by the root, whose sum of vertex values is equal to the | mikhmanoff | NORMAL | 2023-05-04T22:30:24.879494+00:00 | 2023-05-04T22:30:24.879535+00:00 | 3,260 | false | The function hasPathSum checks if there is a path from the root to the leaves in the binary tree defined by the root, whose sum of vertex values is equal to the given number targetSum.\n\nThe function first checks if the root is empty. If it is empty, the function returns false, since an empty tree has no path from the root to the leaves.\n\nThen it subtracts the value of the root from targetSum. It then checks to see if the current node is a leaf, that is, it has no child nodes. If so, the function returns the result of comparing targetSum to zero. If the sum in the current node goes to the right number and the current node is a leaf, then we have found the path from the root to the leaf with the right sum of values.\n\nIf the current node is not a leaf, the function calls itself recursively for the left and right subtree, passing targetSum minus the value of the current node as an argument. The function then returns the result of the logical AND of the recursive calls, since both subtrees must have a path from the root to the leaf with the desired sum in order for the whole tree to have that path.\n\n# Code\n```\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 boolean hasPathSum(TreeNode root, int targetSum) {\n if (root == null) {\n return false;\n }\n\n targetSum -= root.val;\n\n if (root.left == null && root.right == null) {\n return targetSum == 0;\n }\n\n return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum); \n }\n}\n``` | 12 | 0 | ['Python', 'Java', 'Go', 'Python3', 'C#'] | 2 |
path-sum | JavaScript Solution: 98.32% | javascript-solution-9832-by-voltaaage-84si | \nvar hasPathSum = function(root, sum) {\n return dfs(root, 0, sum);\n};\n\nvar dfs = function(curr, currentSum, targetSum) {\n if (!curr) {\n retu | voltaaage | NORMAL | 2020-02-23T09:07:02.009954+00:00 | 2020-02-23T09:07:02.009988+00:00 | 2,874 | false | ```\nvar hasPathSum = function(root, sum) {\n return dfs(root, 0, sum);\n};\n\nvar dfs = function(curr, currentSum, targetSum) {\n if (!curr) {\n return false;\n }\n\n currentSum += curr.val;\n \n if (curr.left === null && curr.right === null) {\n return currentSum === targetSum;\n }\n \n return dfs(curr.left, currentSum, targetSum) || dfs(curr.right, currentSum, targetSum);\n}\n```\n\nRuntime: 56 ms, faster than 98.32% of JavaScript online submissions for Path Sum.\nMemory Usage: 37.1 MB, less than 100.00% of JavaScript online submissions for Path Sum. | 12 | 0 | ['JavaScript'] | 2 |
path-sum | 4 ms C Solution ( Recursion ) | 4-ms-c-solution-recursion-by-rachelwang0-1d3u | bool hasPathSum(struct TreeNode* root, int sum) {\n if (!root) \n return false;\n if (!root->right && !root->left) \n return | rachelwang0831 | NORMAL | 2015-05-22T06:53:07+00:00 | 2015-05-22T06:53:07+00:00 | 1,304 | false | bool hasPathSum(struct TreeNode* root, int sum) {\n if (!root) \n return false;\n if (!root->right && !root->left) \n return sum==root->val;\n return hasPathSum(root->left, sum-root->val)||hasPathSum(root->right, sum-root->val);\n } | 12 | 0 | [] | 0 |
path-sum | 💢☠💫Easiest👾Faster✅💯 Lesser🧠 🎯 C++✅Python3🐍✅Java✅C✅Python🐍✅C#✅💥🔥💫Explained☠💥🔥 Beats 100 | easiestfaster-lesser-cpython3javacpython-z5hx | Intuition\n\n Describe your first thoughts on how to solve this problem. \n- JavaScript Code --> https://leetcode.com/problems/path-sum/submissions/1381986930\n | Edwards310 | NORMAL | 2024-09-07T11:20:24.453547+00:00 | 2024-09-07T11:20:24.453569+00:00 | 2,423 | false | # Intuition\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n- ***JavaScript Code -->*** https://leetcode.com/problems/path-sum/submissions/1381986930\n- ***C++ Code -->*** https://leetcode.com/problems/path-sum/submissions/1381929304\n- ***Python3 Code -->*** https://leetcode.com/problems/path-sum/submissions/1381972482\n- ***Java Code -->*** https://leetcode.com/problems/path-sum/submissions/1381936410\n- ***C Code -->*** https://leetcode.com/problems/path-sum/submissions/1381974650\n- ***Python Code -->*** https://leetcode.com/problems/path-sum/submissions/1381971089\n- ***C# Code -->*** https://leetcode.com/problems/path-sum/submissions/1381983655\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 O(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(N)\n# Code\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} targetSum\n * @return {boolean}\n */\nvar hasPathSum = function(root, targetSum) {\n const dfs = (root, sum, target) => {\n if (!root)\n return false\n sum += root.val\n if (sum == target && !root.left && !root.right)\n return true\n \n return dfs(root.right, sum, target) || dfs(root.left, sum, target)\n }\n\n return dfs(root, 0, targetSum)\n};\n```\n\n | 11 | 0 | ['Tree', 'Depth-First Search', 'Breadth-First Search', 'C', 'Python', 'C++', 'Java', 'Python3', 'JavaScript', 'C#'] | 1 |
path-sum | (✓) 💯 ACCEPTED | 3 LINE CODE | BEATS 100% | JAVA CODE | FASTEST Solution | accepted-3-line-code-beats-100-java-code-ixop | Path Sum\n##### 1) If the tree is empty then false\n##### 2) If there aren\'t any leaf node then return root == k if equal then true else false\n##### 3) And fi | efety | NORMAL | 2024-02-28T17:35:04.315121+00:00 | 2024-02-28T17:35:04.315151+00:00 | 1,980 | false | # Path Sum\n##### 1) If the tree is empty then false\n##### 2) If there aren\'t any leaf node then return root == k if equal then true else false\n##### 3) And finally we find the sum from either left or right node. \n##### 4) Here we subtract each value of those nodes from k thus eventually setp 2 will occur.\n<br><br>\n\n```\n public static boolean hasPathSum(TreeNode root, int k) {\n if (root == null) return false;\n if (root.left == null && root.right == null) return root.val == k;\n return hasPathSum(root.left, k - root.val) || hasPathSum(root.right, k - root.val);\n }\n``` | 11 | 0 | ['Java'] | 0 |
path-sum | Recursive depth-first traversal with sum calculation | recursive-depth-first-traversal-with-sum-5x7p | Intuition\n Describe your first thoughts on how to solve this problem. \nWe need to traverse the tree in a depth-first manner, keeping track of the sum of value | Rare_Zawad | NORMAL | 2023-02-17T18:07:13.950854+00:00 | 2023-02-17T18:07:13.950893+00:00 | 2,010 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to traverse the tree in a depth-first manner, keeping track of the sum of values along the path from the root to the current node. When we reach a leaf node, we check if the sum is equal to the target sum. If yes, we return true, otherwise, we continue traversing the tree.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe define a function `hasPathSum` that takes the root node of the binary tree and the target sum as input, and returns a boolean value indicating whether there exists a root-to-leaf path with the given sum.\n\nThe first base case is when the root is None, which means we have reached the end of a branch without finding the target sum. In this case, we return False.\n\nThe second base case is when the root is a leaf node, which means we have reached the end of a root-to-leaf path. In this case, we check if the sum of values along the path is equal to the target sum. If yes, we return True, otherwise, we return False.\n\nIn the recursive case, we call the `hasPathSum` function on the left and right subtrees, with the target sum reduced by the value of the current node. If either of these recursive calls returns True, we return True, because there exists a root-to-leaf path with the target sum. Otherwise, we continue traversing the tree.\n# Complexity\n- Time complexity:$O(n)$, where n is the number of nodes in the binary tree. We need to visit every node once to check if it is a leaf node and calculate the sum along the path.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$ O(h)$, where h is the height of the binary tree. In the worst case, the recursion stack will have h frames, one for each level of the tree.\n\n\n\n\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 hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n if not root:\n return False\n if not root.left and not root.right: # leaf node\n return targetSum == root.val\n return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)\n``` | 11 | 0 | ['Tree', 'Depth-First Search', 'Breadth-First Search', 'Binary Tree', 'Python3'] | 4 |
path-sum | C++ || 2 different approach || recursive / iterative | c-2-different-approach-recursive-iterati-pv03 | I came up with 2 different approaches for this problem. Please let me know if you have other ideas or if you have suggestions on how to improve one of the solut | heder | NORMAL | 2022-10-04T20:28:13.963202+00:00 | 2022-10-09T17:57:34.016829+00:00 | 1,622 | false | I came up with 2 different approaches for this problem. Please let me know if you have other ideas or if you have suggestions on how to improve one of the solutions. This problem many good solutions have been posted already, nevertheless I just had fun writing up my thoughts. So here we go. :)\n\n\n### Approach 1: recursive\n\nWhen we hear "binary tree" the first reaction should almost always be "recursion", so here we go:\n\n```cpp\n static bool hasPathSum(const TreeNode* root, int targetSum) {\n if (!root) return false;\n \n if (!root->left && !root->right) return root->val == targetSum;\n \n return\n hasPathSum(root->left, targetSum - root->val) ||\n hasPathSum(root->right, targetSum - root->val);\n }\n```\n\nPlease note that the code above is better in case there is actually a path, then the following code without "short circute evaluation":\n\n```cpp\n bool left = hasPathSum(root->left, targetSum - root->val);\n bool right = hasPathSum(root->right, targetSum - root->val);\n return left || right;\n```\n\nThis could be fixed by adding an extra ```if (left) return true;```, but IMO the code above is just the cleanest and shortest solution here.\n\n**Complexity Analysis**\n\nLet $$n$$ be the number of nodes in the tree, and $$h$$ be the height of the tree, which can range from $$\\log n$$ if the tree is perfectly balanced to $$n$$ in the case the tree is basically a linked list.\n\n* Time complexity: $$O(n)$$ worst case we need to visit all the nodes.\n* Space complexity: $$O(h)$$ we need that for the recursion stack.\n\n### Approach 2: iterative\n\nThe iterative version is straight forward as well if we use a ```stack<pair<TreeNode, int>>```.\n\n```cpp\n static bool hasPathSum(const TreeNode* root, int targetSum) {\n if (!root) return false;\n\n stack<pair<const TreeNode*, int>> st;\n st.push({root, targetSum});\n\n while (!empty(st)) {\n const auto [node, target] = st.top(); st.pop();\n if (!node->left && !node->right && node->val == target) return true;\n \n if (node->left) st.push({node->left, target - node->val});\n if (node->right) st.push({node->right, target - node->val});\n }\n \n return false;\n }\n```\n\nWe could use a ```queue``` instead of a ```stack```, but using a BFS like aproach seems a bit pointless to me for this problem. Please let me know if there are good reasons to consider BFS as well.\n\nOne aspect I like about an iterative solution is that it seems easier to handle problematic input. Imagine the tree we get is actually not a tree put has a circle. The solutions above would run out of call stack space or allocate more and more memory and eventually run out of memory. For the iterative version we could easly add something like:\n\n\n```cpp\n if (size(stack) > 10000) {\n LOG_ERROR("Tree too larger or input is not a tree.");\n return false;\n }\n```\n\nHow to best handle the error would be another questions. Do we want to use exceptions or do we want to use a different API to be able to pass the error to the caller is intersting questions to explore.\n\n\n**Complexity Analysis**\nThis is basically the same as for approach 1, but we are using an explict stack instead of the implict call stack, but it would grow at the same speed.\n\n\n_As always: Feedback, questions, and comments are welcome. Leaving an upvote sparks joy! :)_\n\n**p.s. Join us on the [LeetCode The Hard Way Discord Server](https://discord.gg/Nqm4jJcyBf)!** | 11 | 0 | ['Recursion', 'C', 'Iterator'] | 1 |
path-sum | Simple JS Solution w/ Comments | simple-js-solution-w-comments-by-qkrrbtj-ah5c | \nconst hasPathSum = (root, targetSum) => {\n\tif (!root) return false;\n\n\tlet output = false;\n\tconst traverse = (root, sum = 0) => {\n\t\t// if targetSum e | qkrrbtjd90 | NORMAL | 2022-03-17T00:49:25.116756+00:00 | 2022-05-10T17:47:06.953701+00:00 | 627 | false | ```\nconst hasPathSum = (root, targetSum) => {\n\tif (!root) return false;\n\n\tlet output = false;\n\tconst traverse = (root, sum = 0) => {\n\t\t// if targetSum exist at end of path, set output to TRUE\n\t\tif (!root.left && !root.right) {\n\t\t\tif (targetSum === sum + root.val) output = true;\n\t\t}\n\n\t\t// traverse left/right and keep adding value of nodes in current path\n\t\tif (root.left) traverse(root.left, sum + root.val);\n\t\tif (root.right) traverse(root.right, sum + root.val);\n\t};\n\n\ttraverse(root);\n\treturn output;\n};\n``` | 11 | 0 | ['Depth-First Search', 'JavaScript'] | 2 |
path-sum | Java Solution, 0 ms, Beats 100% | java-solution-0-ms-beats-100-by-abstract-aywl | Java Code\n\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * Tree | abstractConnoisseurs | NORMAL | 2023-02-21T05:00:31.326056+00:00 | 2023-02-21T05:00:31.326097+00:00 | 2,727 | false | # Java Code\n```\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 boolean hasPathSum(TreeNode root, int targetSum) {\n if (root == null) {\n return false;\n }\n if (root.val == targetSum && root.left == null && root.right == null) {\n return true;\n }\n return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);\n }\n}\n``` | 10 | 0 | ['Tree', 'Depth-First Search', 'Breadth-First Search', 'Binary Tree', 'Java'] | 1 |
path-sum | Java Recursive Solution | java-recursive-solution-by-kadamyogesh72-i0oj | \nclass Solution {\n public boolean hasPathSum(TreeNode root, int targetSum) {\n if(root==null){\n return false;\n }\n \n | kadamyogesh7218 | NORMAL | 2022-10-04T05:11:34.050964+00:00 | 2022-10-04T05:11:34.051013+00:00 | 968 | false | ```\nclass Solution {\n public boolean hasPathSum(TreeNode root, int targetSum) {\n if(root==null){\n return false;\n }\n \n if(root.left==null && root.right==null && targetSum==root.val){\n return true;\n }\n \n return hasPathSum(root.left,targetSum-root.val) || hasPathSum(root.right,targetSum-root.val);\n\n }\n}\n``` | 10 | 0 | ['Depth-First Search', 'Recursion', 'Binary Tree', 'Java'] | 0 |
path-sum | Three solution to come up on iterview - easy to understand | three-solution-to-come-up-on-iterview-ea-8km8 | Hey there! This problem gives us to practice in use of different binary tree traversals. If you look closer to the idea of the problem you will come up with the | floatfoo | NORMAL | 2022-07-16T20:07:21.426211+00:00 | 2022-07-16T20:07:21.426254+00:00 | 629 | false | Hey there! This problem gives us to practice in use of different binary tree traversals. If you look closer to the idea of the problem you will come up with the following: DFS (**preorder**) with recursion, DFS iterative version and BFS (or level traversal). Go ahead and get to know all of them.\n\n___\n***DFS recursion*** [0ms 44.2MB](https://leetcode.com/submissions/detail/748771650/)\nThe simplies (it\'s seems to me) solution based on **preorder** binary tree traversal. Here we will visit all paths to leaf (node with no children) till we find desired path or visit all:\n\n```\npublic boolean hasPathSum(TreeNode root, int targetSum) {\n if (root == null) return false;\n return hasPathSum(root, targetSum, 0);\n }\n \n private boolean hasPathSum(TreeNode root, int targetSum, int currSum) {\n if (root == null)\n return false;\n currSum += root.val;\n if (currSum == targetSum && root.left == null && root.right == null)\n return true;\n if (hasPathSum(root.left, targetSum, currSum) || hasPathSum(root.right, targetSum, currSum))\n return true;\n return false;\n }\n```\nTime complexity: O(2^n) - where 2^n is a size of a binary tree\nSpace complexity: O(n), where n is a depth of this tree\n\nSimple, readable and neet. But recursion is sign to find iterative method.\n___\n***DFS iterative*** [4ms 44MB](https://leetcode.com/submissions/detail/748798973/)\nThis is an alternative to the previous method because we want to avoid recursion as much as possible. Here we use the same principles (e.g. Stack) as in dfs traversal of binary tree. Note here we have two stacks - one will indicate root - to - this - node sum. If you know how to make it one stack in Java - please let me know ;]\n\n```\npublic boolean hasPathSum(TreeNode root, int targetSum) {\n if (root == null) return false;\n Stack<TreeNode> stack = new Stack<>();\n Stack<Integer> sum = new Stack<>();\n stack.push(root);\n sum.push(root.val);\n while (!stack.isEmpty()) {\n TreeNode node = stack.pop();\n int currSum = sum.pop();\n if (currSum == targetSum && node.left == null && node.right == null)\n return true;\n \n if (node.right != null) {\n stack.push(node.right);\n sum.push(node.right.val + currSum);\n }\n if (node.left != null) {\n stack.push(node.left);\n sum.push(node.left.val + currSum);\n }\n }\n return false;\n }\n```\nTime and Space complexity are identical to the first approach.- But it\'s generally better the previous because recursion may cause stackoverflow\n\n____\n***BFS*** [2ms 44.6MB](https://leetcode.com/submissions/detail/748810508/)\nThe last approach is so called level traversal - that is, we initially visit one level of the tree, then one that below and so on. We use the standart approach for BFS with queue. Note the same issue with the second queue for sum.\nIt is so much a like previous in implemention, but the data structure dictates an order - stack makes traversal go in depth, when queue makes us check this level first.\n\n```\npublic boolean hasPathSum(TreeNode root, int targetSum) {\n if (root == null) return false;\n Queue<TreeNode> queue = new LinkedList<>();\n Queue<Integer> sum = new LinkedList<>();\n queue.add(root);\n sum.add(root.val);\n while (!queue.isEmpty()) {\n int size = queue.size();\n for (int i = 0; i < size; i++) {\n TreeNode node = queue.remove();\n int currSum = sum.remove();\n if (currSum == targetSum && node.left == null && node.right == null) {\n return true;\n }\n \n \n if (node.left != null) {\n queue.add(node.left);\n sum.add(node.left.val + currSum);\n }\n if (node.right != null) {\n queue.add(node.right);\n sum.add(node.right.val + currSum);\n }\n }\n }\n return false;\n }\n```\nAgain, time and space complexity stay the same.\n___\nIn conclusion, benchmarks shows recursive is the best.and BFS is best among iterative version. Still you need to look in the root of the problem and choose the most preferable ( but here I belive it doesn\'t matter much )\n | 10 | 0 | ['Breadth-First Search', 'Recursion', 'Iterator', 'Java'] | 1 |
path-sum | Java || 100% Faster || Recursion | java-100-faster-recursion-by-sherriecao-4836 | Please upvote if it helps! Thx :D\n\npublic boolean hasPathSum(TreeNode root, int targetSum) {\n\tif (root == null) return false;\n\tif (root.left == null && ro | SherrieCao | NORMAL | 2021-12-29T07:37:20.477737+00:00 | 2021-12-29T07:37:20.477780+00:00 | 711 | false | ## Please upvote if it helps! Thx :D\n```\npublic boolean hasPathSum(TreeNode root, int targetSum) {\n\tif (root == null) return false;\n\tif (root.left == null && root.right==null && root.val == targetSum) return true;\n\ttargetSum -= root.val;\n\treturn hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);\n}\n``` | 10 | 0 | ['Recursion', 'Java'] | 1 |
path-sum | [Python3] recursively and iteratively | python3-recursively-and-iteratively-by-z-kbvh | recursively:\n\nclass Solution:\n def hasPathSum(self, root: TreeNode, sum: int) -> bool:\n if not root:\n return False\n sum -= roo | zhanweiting | NORMAL | 2019-08-03T23:10:48.131673+00:00 | 2019-08-03T23:18:27.180808+00:00 | 1,659 | false | recursively:\n```\nclass Solution:\n def hasPathSum(self, root: TreeNode, sum: int) -> bool:\n if not root:\n return False\n sum -= root.val\n if not root.left and not root.right:\n return sum == 0\n return self.hasPathSum(root.left,sum) or self.hasPathSum(root.right,sum)\n```\nIteratively:\n```\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 hasPathSum(self, root: TreeNode, sum: int) -> bool:\n if not root:\n return False\n stack = [[root,sum-root.val]]\n while stack:\n cur,curr_sum = stack.pop()\n if not cur.left and not cur.right and curr_sum == 0:\n return True\n if cur.right:\n stack.append((cur.right,curr_sum-cur.right.val))\n if cur.left:\n stack.append((cur.left, curr_sum-cur.left.val))\n return False\n``` | 10 | 0 | ['Python', 'Python3'] | 0 |
path-sum | Python3 deque beat 98.10% 34ms | python3-deque-beat-9810-34ms-by-amitpand-js6w | \n\n# 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) | amitpandit03 | NORMAL | 2023-03-24T17:26:23.586818+00:00 | 2023-03-24T17:26:23.586857+00:00 | 5,669 | false | \n\n# 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```\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 hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n if not root:\n return False\n queue = collections.deque([(root, root.val)])\n while queue:\n node, val = queue.popleft()\n if not node.left and not node.right:\n if val == targetSum: return True\n else: continue\n if node.left:\n queue.append((node.left, val + node.left.val)) \n if node.right:\n queue.append((node.right, val + node.right.val)) \n return False\n``` | 9 | 0 | ['Tree', 'Depth-First Search', 'Breadth-First Search', 'Binary Tree', 'Python3'] | 1 |
path-sum | 1-line Python | 1-line-python-by-alex391a-nvwr | \nclass Solution:\n def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n return (root.val == targetSum) if (root and not root.lef | alex391a | NORMAL | 2022-10-04T05:52:17.831334+00:00 | 2022-10-19T09:10:53.141071+00:00 | 1,117 | false | ```\nclass Solution:\n def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n return (root.val == targetSum) if (root and not root.left and not root.right) else (root and (self.hasPathSum(root.right, targetSum - root.val) or self.hasPathSum(root.left, targetSum - root.val)))\n``` | 9 | 0 | ['Python3'] | 1 |
path-sum | Python 3 || 7 lines, recursion || T/S: 85% / 86% | python-3-7-lines-recursion-ts-85-86-by-s-3bqa | \nclass Solution:\n def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:\n \n if not root : | Spaulding_ | NORMAL | 2022-10-04T00:27:03.971132+00:00 | 2024-05-26T20:35:06.720121+00:00 | 388 | false | ```\nclass Solution:\n def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:\n \n if not root : # if null node\n return False # return False\n \n if (not root.right and not root.left # if target hit on leaf, \n and root.val == targetSum): # return True\n return True\n \n return (self.hasPathSum(root.left ,targetSum-root.val) or # traverse left subtree\n self.hasPathSum(root.right,targetSum-root.val)) # traverse right subtree \n```\n[https://leetcode.com/problems/path-sum/submissions/1268835907/](https://leetcode.com/problems/path-sum/submissions/1268835907/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*H*), in which *N* ~ the number of nodes and *H* ~ the height of the tree.\n\n | 9 | 0 | ['Recursion', 'Python'] | 1 |
path-sum | [C++] 100% Time, one-line recursive solution | c-100-time-one-line-recursive-solution-b-5545 | The base case is when the root->val == sum and the node is a leaf (ie: both !root-left and !root->right are true); if not, we keep recursing with decreased valu | ajna | NORMAL | 2020-06-16T18:38:44.494942+00:00 | 2020-06-16T18:38:44.494978+00:00 | 906 | false | The base case is when the `root->val == sum` and the node is a leaf (ie: both `!root-left` and `!root->right` are true); if not, we keep recursing with decreased values of `sum`:\n\nNotice that since the nodes can also have negative values, there is no way to know in advance when you have summed "too much" and thus you should stop exploring down.\n\n```cpp\nclass Solution {\npublic:\n bool hasPathSum(TreeNode* root, int sum) {\n return root && (!root->left && !root->right && root->val == sum || hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val));\n }\n};\n``` | 9 | 1 | ['Recursion', 'C', 'C++'] | 1 |
path-sum | javaScript | javascript-by-suxiaohui1996-9myo | \nvar hasPathSum = function(root, sum) {\n if(!root) {\n return false;\n }\n if(!root.left && !root.right) {\n return root.val == sum ? t | suxiaohui1996 | NORMAL | 2020-02-28T09:19:23.905770+00:00 | 2020-02-28T09:19:23.905802+00:00 | 945 | false | ```\nvar hasPathSum = function(root, sum) {\n if(!root) {\n return false;\n }\n if(!root.left && !root.right) {\n return root.val == sum ? true : false;\n }\n let remain = sum - root.val\n return hasPathSum(root.left, remain) || hasPathSum(root.right, remain)\n};\n``` | 9 | 0 | [] | 0 |
path-sum | Java solution, shortest!!! | java-solution-shortest-by-erhu-aj12 | public boolean hasPathSum(TreeNode root, int sum) {\n if (root == null) {\n return false;\n }\n\n if (sum - root.val == 0 && roo | erhu | NORMAL | 2015-03-09T07:59:03+00:00 | 2015-03-09T07:59:03+00:00 | 1,596 | false | public boolean hasPathSum(TreeNode root, int sum) {\n if (root == null) {\n return false;\n }\n\n if (sum - root.val == 0 && root.left == null && root.right == null) {\n return true;\n }\n\n return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);\n } | 9 | 0 | [] | 0 |
path-sum | Share my easy and clean recursion Java solution with explanation | share-my-easy-and-clean-recursion-java-s-iart | public class Solution {\n public boolean hasPathSum(TreeNode root, int sum) {\n \n // check if root is null\n if(root == | nlackx | NORMAL | 2015-09-24T15:37:55+00:00 | 2015-09-24T15:37:55+00:00 | 989 | false | public class Solution {\n public boolean hasPathSum(TreeNode root, int sum) {\n \n // check if root is null\n if(root == null) return false;\n \n // if the current node is not a leaf node, do recursion.\n if(root.left != null || root.right != null) \n return hasPathSum(root.left, sum - root.val) || \n hasPathSum(root.right, sum - root.val);\n \n // now the current node is a leaf node\n return sum - root.val == 0;\n }\n } | 9 | 0 | [] | 0 |
path-sum | Java iterative solution with one stack | java-iterative-solution-with-one-stack-b-q2wq | \npublic boolean hasPathSum(TreeNode root, int sum) {\n Stack<TreeNode> visitedNodes = new Stack<>();\n TreeNode prev = null;\n \n wh | upthehell | NORMAL | 2017-04-17T22:28:18.375000+00:00 | 2017-04-17T22:28:18.375000+00:00 | 764 | false | ```\npublic boolean hasPathSum(TreeNode root, int sum) {\n Stack<TreeNode> visitedNodes = new Stack<>();\n TreeNode prev = null;\n \n while(root!=null || !visitedNodes.isEmpty()){\n while(root!=null){\n visitedNodes.push(root);\n sum -= root.val;\n prev = root;\n root = root.left;\n }\n root = visitedNodes.peek();\n if(root.left==null && root.right == null && sum==0) return true;\n if(root.right != null && root.right != prev){\n root = root.right;\n }else{\n sum += root.val;\n prev = visitedNodes.pop();\n root = null;\n }\n }\n \n return false;\n }\n\n``` | 9 | 0 | [] | 1 |
path-sum | ✅💯🔥Simple Code🚀📌|| 🔥✔️Easy to understand🎯 || 🎓🧠Beats 100%🔥|| Beginner friendly💀💯 | simple-code-easy-to-understand-beats-100-w2b7 | 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 | atishayj4in | NORMAL | 2024-08-01T20:11:08.270210+00:00 | 2024-08-01T20:11:08.270229+00:00 | 975 | 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 * 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 boolean hasPathSum(TreeNode root, int targetSum) {\n return pathsum(root, 0, targetSum);\n }\n public boolean pathsum(TreeNode root, int sum, int targetSum){\n if(root==null){\n return false;\n }\n if(root.left == null && root.right == null){\n sum = sum + root.val;\n if(sum == targetSum){\n return true;\n } \n } \n return pathsum(root.left, sum+root.val, targetSum) || pathsum(root.right, sum+=root.val, targetSum);\n }\n}\n```\n | 8 | 0 | ['Tree', 'Depth-First Search', 'Breadth-First Search', 'C', 'Binary Tree', 'Python', 'C++', 'Java'] | 0 |
path-sum | C++ and Python3 || DFS || Simple and Optimal | c-and-python3-dfs-simple-and-optimal-by-q3g9h | \n> \n\n# Code\nC++ []\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * | meurudesu | NORMAL | 2024-02-24T09:23:22.468875+00:00 | 2024-02-24T09:23:22.468897+00:00 | 2,268 | false | > \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 */\nclass Solution {\npublic:\n bool helper(TreeNode* node, int targetSum) {\n if(node == NULL) return false;\n if(node->val == targetSum && node->left == NULL && node->right == NULL) return true;\n return helper(node->left, targetSum - node->val) ||\n helper(node->right, targetSum - node->val);\n }\n\n bool hasPathSum(TreeNode* root, int targetSum) {\n if(root == NULL) return NULL;\n return helper(root, targetSum);\n }\n};\n```\n```Python3 []\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 hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n def helper(node, currSum):\n if not node:\n return False\n currSum += node.val\n if not node.left and not node.right:\n return currSum == targetSum\n return helper(node.left, currSum) or helper(node.right, currSum)\n if not root:\n return None\n return helper(root, 0)\n``` | 8 | 0 | ['Tree', 'Depth-First Search', 'Recursion', 'Binary Tree', 'C++', 'Python3'] | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.