-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path21. RangeSumOfBST.py
34 lines (26 loc) · 1.05 KB
/
21. RangeSumOfBST.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#Problem Statement available at:https://leetcode.com/problems/range-sum-of-bst/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
if not root:
return 0
else:
queue = []
sum_lst = []
queue.append(root)
while(queue):
node = queue.pop()
if(node.val >= L and node.val<= R):
sum_lst.append(node.val)
#Add the subnode only if current node value is greater then left range and less then right range
if node.left and node.val >= L:
queue.append(node.left)
if node.right and node.val <= R:
queue.append(node.right)
#print (sum(sum_lst))
return sum(sum_lst)