Skip to content

Commit 3792c44

Browse files
author
rajitbanerjee
committed
range sum of bst
1 parent 94676d1 commit 3792c44

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ My solutions to some problems from [LeetCode](https://leetcode.com/problemset/al
5252
| 690 | [Employee Importance][690] | [Python][690a] | Easy |
5353
| 700 | [Search in a Binary Search Tree][700] | [Python][700a] | Easy |
5454
| 788 | [Rotated Digits][788] | [Python][788a] | Easy |
55+
| 938 | [Range Sum of BST][938] | [Python][938a] | Easy |
5556
| 1029 | [Two City Scheduling][1029] | [Python][1029a] | Easy |
5657
| 1137 | [N-th Tribonacci Number][1137] | [Java][1137a] | Easy |
5758
| 1275 | [Find Winner on a Tic Tac Toe Game][1275] | [Python][1275a] | Easy |
@@ -153,6 +154,8 @@ My solutions to some problems from [LeetCode](https://leetcode.com/problemset/al
153154
[700a]: ./src/searchBST/search.py
154155
[788]: https://leetcode.com/problems/rotated-digits/
155156
[788a]: ./src/rotatedDigits/dig.py
157+
[938]: https://leetcode.com/problems/range-sum-of-bst/
158+
[938a]: ./src/rangeSumBST/sum.py
156159
[1029]: https://leetcode.com/problems/two-city-scheduling/
157160
[1029a]: ./src/twoCityScheduling/sched.py
158161
[1137]: https://leetcode.com/problems/n-th-tribonacci-number/

src/rangeSumBST/sum.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Definition for a binary tree node.
2+
class TreeNode:
3+
def __init__(self, val=0, left=None, right=None):
4+
self.val = val
5+
self.left = left
6+
self.right = right
7+
8+
9+
class Solution:
10+
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
11+
if not root:
12+
return 0
13+
total = 0
14+
# if node value is within range, add to total
15+
if L <= root.val <= R:
16+
total += root.val
17+
# repeat process for sub-trees
18+
total += self.rangeSumBST(root.left, L, R)
19+
total += self.rangeSumBST(root.right, L, R)
20+
return total

0 commit comments

Comments
 (0)