DEV Community

Cover image for Day 13 of 100 days dsa coding challenge
Manasi Patil
Manasi Patil

Posted on

Day 13 of 100 days dsa coding challenge

Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! πŸ’»πŸ”₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! πŸš€

100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney

Problem:

https://www.geeksforgeeks.org/problems/range-sum-of-bst/1

Sum of Nodes in BST Range

Difficulty: Medium Accuracy: 87.35%

Given the root of a Binary Search Tree and two integers l and r, the task is to find the sum of all nodes that lie between l and r, including both l and r.
Examples
Input: root = [22, 12, 30, 8, 20], l = 10, r = 22


Output: 54
Explanation: The nodes in the given Tree that lies in the range [10, 22] are {12, 20, 22}. Therefore, the sum of nodes is 12 + 20 + 22 = 54.

Input: root = [8, 5, 11, 3, 6, N, 20], l = 11, r = 15


Output: 11
Explanation: The nodes in the given Tree that lies in the range [11, 15] is {11}. Therefore, the sum of node is 11.
Constraints:
0 ≀ number of nodes ≀ 104
0 ≀ node->data ≀ 104
0 ≀ l ≀ r ≀ 104

Solution:
class Solution:
def nodeSum(self, root, l, r):
if not root:
return 0
if root.data < l:
return self.nodeSum(root.right, l, r)
elif root.data > r:
return self.nodeSum(root.left, l, r)
else:
return root.data + self.nodeSum(root.left, l, r) + self.nodeSum(root.right, l, r)

Top comments (0)