Shelf Index Check

Medium · Trees & BSTs · about 20 min

A library keeps its shelf index as a binary tree of call numbers, where duplicates always go to the left. The index is valid when, for every node:

  • every key in its left subtree is less than or equal to the node's key, and
  • every key in its right subtree is strictly greater than the node's key.

The tree is a level-order list: the root first, then each node's left and right child in turn, with None (Python) / null (JavaScript) for a missing child. A build(level) helper in the starter turns it into nodes with .val, .left and .right.

Return True / true if the index is valid, otherwise False / false. An empty index is valid.

  • Up to 10,000 nodes, keys are any 32-bit integers (from -2147483648 to 2147483647).

Examples:

shelf_index_ok([2, 2, 3]) → True (the duplicate 2 is on the left)

shelf_index_ok([2, 1, 2]) → False (the duplicate 2 is on the right)

Hints

  • A node's parent is not the only ancestor that limits it.
  • Pass a lower and an upper limit down the tree, and tighten one of them at each step.
  • Decide carefully which limit is inclusive: equal keys may only be on the left.

Learn the pattern first: the Trees & BSTs lesson.

More Trees & BSTs problems