|
| 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