Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4dc1231

Browse files
Create range_sum_of_bst.py
1 parent 49282a8 commit 4dc1231

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

‎day-24/range_sum_of_bst.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Problem: Range Sum of BST
2+
# Link: https://leetcode.com/problems/range-sum-of-bst/description/
3+
# Tags: Tree, BST, DFS, Recursion
4+
# Approach: Use BST properties to prune traversal. If node.val < low, skip the left subtree;
5+
# if node.val > high, skip the right subtree. Otherwise include node.val and recurse
6+
# into both sides. This avoids visiting irrelevant branches.
7+
# Time Complexity: O(m) where m is the number of visited nodes (≤ n), best-case prunes large parts
8+
# Space Complexity: O(h) recursion stack, where h is the tree height
9+
10+
11+
class Solution:
12+
def rangeSumBST(self, root, low, high):
13+
if not root:
14+
return 0
15+
if root.val < low:
16+
return self.rangeSumBST(root.right, low, high) # all left < root.val < low -> skip left
17+
if root.val > high:
18+
return self.rangeSumBST(root.left, low, high) # all right > root.val > high -> skip right
19+
20+
# low <= root.val <= high
21+
return (root.val
22+
+ self.rangeSumBST(root.left, low, high)
23+
+ self.rangeSumBST(root.right, low, high))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /