Skip to content

Commit 99094a6

Browse files
committed
Range Sum of BST
1 parent 8f942a2 commit 99094a6

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

938-range-sum-of-bst.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/range-sum-of-bst/
3+
4+
Given the root node of a binary search tree, return the sum of values of all nodes with value
5+
between L and R (inclusive).
6+
The binary search tree is guaranteed to have unique values.
7+
8+
Example 1:
9+
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
10+
Output: 32
11+
12+
Example 2:
13+
Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
14+
Output: 23
15+
16+
Note:
17+
The number of nodes in the tree is at most 10000.
18+
The final answer is guaranteed to be less than 2^31.
19+
"""
20+
# Definition for a binary tree node.
21+
# class TreeNode:
22+
# def __init__(self, x):
23+
# self.val = x
24+
# self.left = None
25+
# self.right = None
26+
27+
class Solution:
28+
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
29+
def dfs(node):
30+
if node:
31+
if L<= node.val <= R:
32+
self.ans += node.val
33+
if L < node.val:
34+
dfs(node.left)
35+
if node.val < R:
36+
dfs(node.right)
37+
self.ans = 0
38+
dfs(root)
39+
return self.ans

0 commit comments

Comments
 (0)