938. Range Sum of BST
Tre, DFS, BFS, BT ·Problem Statement
link: LeetCode.cn LeetCode
Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].
Example:
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23
Constraints:
The number of nodes in the tree is in the range [1, 2 * 10^4]. 1 <= Node.val <= 10^5 1 <= low <= high <= 10^5 All Node.val are unique.
Solution Approach
The algorithm traverses the binary search tree (BST) using either depth-first search (DFS) or breadth-first search (BFS) to accumulate the sum of node values that fall within the given range [low, high], efficiently skipping branches that do not contribute to the result.
Algorithm
- Range Filtering: The algorithm efficiently skips subtrees that are outside the given range [low, high], avoiding unnecessary computation by checking node values before traversing their children.
- Traversal Methods: Both depth-first search (DFS) and breadth-first search (BFS) approaches are utilized to visit nodes within the specified range, accumulating the sum of valid node values.
- Early Stopping: The algorithm leverages BST properties, such as left and right subtrees’ value constraints, to stop traversing paths that cannot contain values within the range, improving performance.
Complexity
time complexity: O(n) space complexity: O(h)
Implement
# 10 # /\ # 5 15 # /\ \ # 3 7 18 class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
if not root:
return 0
if root.val > high:
return self.rangeSumBST(root.left, low, high)
if root.val < low:
return self.rangeSumBST(root.right, low, high)
return root.val + self.rangeSumBST(root.left, low, high) + self.rangeSumBST(root.right, low, high)
class Solution:
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
total = 0
q = collections.deque([root])
while q:
node = q.popleft()
if not node:
continue
if node.val > high:
q.append(node.left)
elif node.val < low:
q.append(node.right)
else:
total += node.val
q.append(node.left)
q.append(node.right)
return total