Sum of Keys Within a Value Window in a Serialized BST
Trees & GraphsAuto-graded · 17 test casesLast updated
Rebuild a BST from a level-order list and sum the node values inside an inclusive range, using ordering to skip subtrees that cannot contain qualifying values.
You are given a binary search tree (BST) with distinct integer keys, encoded as a level-order list, along with two integers lower and upper. Return the sum of all node values v that satisfy lower <= v <= upper.
Input format
nodes is the tree in level-order (breadth-first) form, where None marks an absent child:
- The first element is the root. If the list is empty, or its first element is
None, the tree is empty. - Process nodes in the order they were created. Each real node takes the next two entries of the list as its left child and right child, in that order. A
Noneentry means that child does not exist. - A
Nonenode never receives children, so no entries are consumed on its behalf. - If the list ends before all child slots are filled, the remaining children are simply absent.
Task
Rebuild the tree from nodes, then compute the sum of every value v with lower <= v <= upper (both ends inclusive). Return 0 if no node qualifies or the tree is empty.
Aim to use the BST ordering so that subtrees that cannot contain any value in the range are never visited.
Constraints
0 <= len(nodes) <= 10^4(a typical bound; the tree may be heavily skewed)- Node values and the bounds are integers, and may be negative.
- All node values are distinct, and the tree satisfies the standard BST property.
lower <= upper- The function returns a single integer.
Examples
Example 1
Input: bst_window_sum([10, 5, 15, 3, 7, None, 18], 7, 15)
Output: 32
Example 2
Input: bst_window_sum([10, 5, 15, 3, 7, 13, 18, 1, None, 6], 6, 10)
Output: 23
Hints
Hint 1
Start by turning the level-order list into real nodes using a queue: each non-null node consumes the next two list entries as its left and right children.
Hint 2
For a node with value v, the left subtree only holds values smaller than v, so it can matter only if v > lower. The right subtree only holds larger values, so it can matter only if v < upper.
Hint 3
Decide whether to add a node's value separately from deciding which children to visit. A node below the range can still have a right subtree that lands inside it. An explicit stack avoids recursion-depth trouble on skewed trees.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
-
Rebuild the tree. Walk the level-order list with a queue. Each real node that is dequeued takes the next two list entries as its left and right children. A
Noneentry creates no node, and nothing is queued for it. -
Traverse with pruning. Use an explicit stack starting at the root. For each popped node with value
v:- If
lower <= v <= upper, addvto the total. - Push the left child only if
v > lower. Everything in the left subtree is smaller thanv, so ifv <= lower, nothing there can exceedlower(and with distinct keys, nothing there can equal it either). - Push the right child only if
v < upper. Everything in the right subtree is larger thanv, so ifv >= upper, nothing there can be at mostupper.
- If
The node's own value is checked independently of the pruning rules. A node smaller than lower is not counted, but its right subtree is still explored, since it may contain values in range.
Why it is correct
Take any node x with value in [lower, upper]. Every ancestor a of x lies on the path from the root. If x is in a's left subtree, then lower <= x.val < a.val, so a.val > lower and the traversal goes left. If x is in a's right subtree, then a.val < x.val <= upper, so a.val < upper and the traversal goes right. So every edge on the path is followed, and x is visited exactly once and counted. The only subtrees skipped are those proven to lie entirely outside the range, so no qualifying node is missed and none is counted twice.
Complexity
Let n be the number of nodes, h the height and k the number of nodes in range.
- Building the tree: O(n) time and O(n) space.
- Traversal: O(k + h) time with pruning (the in-range nodes plus out-of-range nodes along the two boundary paths), O(n) in the worst case.
- Traversal extra space: O(h) for the stack, which is O(n) for a skewed tree.
Using an explicit stack rather than recursion avoids Python's recursion limit on very deep, skewed trees.
Reference solution
from typing import List, Optional
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def build_tree(values):
if not values or values[0] is None:
return None
root = Node(values[0])
queue = [root]
index = 1
head = 0
while head < len(queue) and index < len(values):
node = queue[head]
head += 1
if index < len(values) and values[index] is not None:
node.left = Node(values[index])
queue.append(node.left)
index += 1
if index < len(values) and values[index] is not None:
node.right = Node(values[index])
queue.append(node.right)
index += 1
return root
def bst_window_sum(nodes: List[Optional[int]], lower: int, upper: int) -> int:
root = build_tree(nodes)
total = 0
stack = [root] if root else []
while stack:
node = stack.pop()
if lower <= node.val <= upper:
total += node.val
if node.left is not None and node.val > lower:
stack.append(node.left)
if node.right is not None and node.val < upper:
stack.append(node.right)
return total