Given a binary search tree with distinct node values and two integers low and high, return the sum of every node value v with low <= v <= high. Return 0 if no value falls in the range.
In a binary search tree, for every node, all values in its left subtree are smaller than the node's value and all values in its right subtree are larger.
Function Signature
def range_sum_bst(tree: list[int | None], low: int, high: int) -> int:
Rules
-
Input format.
tree
is the level-order serialization of the tree.
tree[0]
is the root; after it, entries are consumed two at a time as the left child and then the right child of each non-null node, in the order those nodes appear.
None
marks a missing child, children of missing nodes are not listed, and trailing
None
entries may be omitted.
-
The input is guaranteed to be a valid binary search tree.
-
Both bounds are inclusive.
Constraints
-
1 <= number of nodes <= 20000
-
1 <= node value <= 100000
, and all values are distinct.
-
1 <= low <= high <= 100000
-
The result fits in a signed 32-bit integer.
Examples
Example 1
Input: tree = [10, 5, 15, 3, 7, None, 18], low = 7, high = 15
Output: 32
Explanation: the values in range are 7, 10, and 15.
Example 2
Input: tree = [10, 5, 15, 3, 7, 13, 18, 1, None, 6], low = 6, high = 10
Output: 23
Explanation: the values in range are 6, 7, and 10.
Example 3
Input: tree = [10, 5, 15], low = 11, high = 14
Output: 0
Explanation: no value lies between 11 and 14.