1+ ##==================================
2+ ## Leetcode
3+ ## Student: Vandit Jyotindra Gajjar
4+ ## Year: 2020
5+ ## Problem: 938
6+ ## Problem Name: Range Sum of BST
7+ ##===================================
8+ #
9+ #Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
10+
11+ #The binary search tree is guaranteed to have unique values.
12+ #
13+ #Example 1:
14+ #
15+ #Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
16+ #Output: 32
17+ #
18+ #Example 2:
19+ #
20+ #Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
21+ #Output: 23
22+ class Solution ;
23+ def rangeSumBST (self , root , L , R ):
24+ return self ._rangeSumBST (root , L , R , 0 ) #Calling our helper method
25+ def _rangeSumBST (self , curr_node , L , R , Sum ): #Defining our helper method
26+ if curr_node is None : #Condition-check: If curr_node is empty
27+ return Sum #We return Sum
28+ if L <= curr_node .val <= R : #Condition-check: If our curr_node.val is in the range of [L, R]
29+ Sum += curr_node .val #Sum is Sum + curr_node.val
30+ Sum = self ._rangeSumBST (curr_node .left , L , R , Sum ) #Calling helper method
31+ Sum = self ._rangeSumBST (curr_node .right , L , R , Sum ) #Calling helper method
32+ if curr_node .val < L : #Condition-check: if curr_node.val is less than L
33+ Sum = self ._rangeSumBST (curr_node .right , L , R , Sum ) #Calling helper method
34+ if curr_node .val > R : #Condition-check: if curr_node.val is greater than R
35+ Sum = self ._rangeSumBST (curr_node .left , L , R , Sum ) #Calling helper method
36+ return Sum #Return total Sum at the end.
0 commit comments