KatInterview

Sum of Keys Within a Value Window in a Serialized BST

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsbinary-search-treedfstree-construction

Last 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 None entry means that child does not exist.
  • A None node 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.