Leetcode 938: Range Sum of BST

grid47
grid47
Exploring patterns and algorithms
Aug 5, 2024 5 min read

Given the root of a binary search tree and two integers, low and high, return the sum of values of all nodes whose values are within the inclusive range [low, high]. You can assume that all nodes in the tree have distinct values.
Problem
Approach
Steps
Complexity
Input: The input consists of the root of a binary search tree and two integers, low and high.
Example: Input: root = [12,8,15,6,10,14,18], low = 8, high = 15
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.
Output: Return the sum of all node values within the range [low, high].
Example: Output: 35
Constraints:
• The sum should be within the range of integer values.
Goal: Traverse the binary search tree and calculate the sum of all nodes with values in the range [low, high]. Use a recursive or iterative approach to explore the tree and accumulate the sum.
Steps:
• 1. Perform an in-order traversal of the tree.
• 2. For each node, check if its value is within the given range [low, high].
• 3. If the value is within range, add it to the sum.
• 4. Return the accumulated sum after traversing all the nodes.
Goal: The tree may contain a large number of nodes, so ensure the solution is efficient enough to handle up to 20,000 nodes.
Steps:
• 1 <= n <= 20000
• 1 <= Node.val <= 100000
• 1 <= low <= high <= 100000
• All node values are unique.
Assumptions:
• The tree is a binary search tree, so the nodes follow the binary search property: left child < root < right child.
Input: Input: root = [12,8,15,6,10,14,18], low = 8, high = 15
Explanation: In this case, the nodes in the range [8, 15] are 8, 10, 12, and 15. The sum of these values is 35.

Input: Input: root = [12,8,15,6,10,14,18], low = 10, high = 18
Explanation: The nodes in the range [10, 18] are 10, 12, 15, and 14. The sum of these values is 51.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus