
Problem Statement
In this problem, we are provided with a binary search tree (BST) and two integers, low
and high
. Our task is to compute the sum of the values of all nodes whose values fall within the inclusive range [low, high]
. The BST is defined such that for each node, the left subtree only contains nodes with values less than the node's value, and the right subtree only contains nodes with values greater than the node's value. Each node in the BST contains a unique value, making our search straightforward as there are no duplicate values to handle. The challenge lies in efficiently traversing the tree and aggregating the sum.
Examples
Example 1
Input:
root = [10,5,15,3,7,null,18], low = 7, high = 15
Output:
32
Explanation:
Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.
Example 2
Input:
root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output:
23
Explanation:
Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.
Constraints
- The number of nodes in the tree is in the range
[1, 2 * 104]
. 1 <= Node.val <= 105
1 <= low <= high <= 105
- All
Node.val
are unique.
Approach and Intuition
Understanding the Binary Search Tree (BST) properties:
- Nodes to the left of a parent have values less than the parent.
- Nodes to the right have values greater than the parent.
- This property ensures that traversal can be done selectively, skipping entire subtrees whose values do not fall within the desired range.
Strategy to solve the problem:
- Traverse the tree starting from the root.
- Use recursion or iteration to explore nodes.
- At each node, decide whether to move left, right, or to sum up the node based on its value relative to
low
andhigh
.
Detailed decision-making:
- If the value of the current node is less than
low
, skip the left subtree since all those values are also less. - If the value is greater than
high
, skip the right subtree. - If the node value is within the range
[low, high]
, include its value in the sum and continue to explore both subtrees.
- If the value of the current node is less than
Efficiency considerations:
- Due to the properties of BST, not all nodes are necessarily visited. Only nodes that potentially fall within the range
[low, high]
or are needed to reach such nodes are visited. - Therefore, the algorithm could perform faster than a simple linear traversal of all nodes.
- Due to the properties of BST, not all nodes are necessarily visited. Only nodes that potentially fall within the range
By leveraging the properties of the BST and using selective traversal, we can efficiently compute the sum of node values that fall within a specified range, often skipping large portions of the tree that do not need to be explored. This problem highlights the effectiveness of understanding underlying data structures for optimal algorithmic solutions.
Solutions
- Java
class Solution {
public int sumRangeBST(TreeNode node, int L, int H) {
int total = 0;
Stack<TreeNode> nodes = new Stack();
nodes.push(node);
while (!nodes.isEmpty()) {
TreeNode current = nodes.pop();
if (current != null) {
if (L <= current.val && current.val <= H)
total += current.val;
if (L < current.val)
nodes.push(current.left);
if (current.val < H)
nodes.push(current.right);
}
}
return total;
}
}
This Java solution uses a non-recursive approach to calculate the sum of values within a specified range [L, H]
in a Binary Search Tree (BST). The method, sumRangeBST(TreeNode node, int L, int H)
, utilizes a Stack<TreeNode>
to iterate through the tree without recursion.
The algorithm works as follows:
- Initialize
total
to store the sum of nodes' values that fall within the range. - Create and initialize a
Stack<TreeNode>
and push the root node onto the stack. - Use a while loop to process nodes until the stack is empty:
- Pop the top node from the stack.
- If the node is not null, check if node's value is within the
[L, H]
. If so, add the value tototal
. - Depending on the node's value, decide whether to traverse left or right:
- If node's value is greater than
L
, push the left child to the stack. - If node's value is less than
H
, push the right child to the stack.
- If node's value is greater than
With this implementation, you efficiently explore only the relevant parts of the BST, avoiding unnecessary traversal and achieving optimized performance especially for larger trees. This method ensures a stack-based DFS execution where only relevant subtrees are explored based on the comparison with limits L
and H
. It is a robust solution handling the structure and constraints of BST efficiently.
- Python
class Solution:
def sumBST(self, node_root: Optional[TreeNode], min_val: int, max_val: int) -> int:
total = 0
nodes = [node_root]
while nodes:
current = nodes.pop()
if current:
if min_val <= current.val <= max_val:
total += current.val
if min_val < current.val:
nodes.append(current.left)
if current.val < max_val:
nodes.append(current.right)
return total
The solution presented outlines a method to calculate the sum of values of all nodes in a binary search tree (BST) that fall within a given range, defined by min_val
and max_val
. This Python function named sumBST
uses a non-recursive, iterative approach to traverse the BST while accumulating the sum of node values that respect the range criteria.
Here's a breakdown of the procedure:
- Initialize a variable
total
to zero to store the cumulative sum of node values that fall within the specified range. - Create a list
nodes
initially consisting of thenode_root
, which acts as a stack to manage the nodes yet to be processed. - Utilize a
while
loop that continues as long as there are nodes in thenodes
list:- Extract the latest node from the stack using
pop()
. - Check if the node exists:
- If the node's value falls within
min_val
andmax_val
, add its value tototal
. - Add the node's children to the stack based on whether their values could potentially fall within the given range:
- The left child is added if
min_val
is less than the current node's value. - The right child is added if the current node's value is less than
max_val
.
- The left child is added if
- If the node's value falls within
- Extract the latest node from the stack using
- Return the accumulated value in
total
upon completion of the loop.
This function effectively balances the traversal without the need for recursion, ensuring efficient handling of large data structures by using an iterative approach with a stack. Its check before traversal of child nodes also minimizes unnecessary operations, promoting faster computation by focusing only on relevant portions of the BST.
No comments yet.