Problem 445056 · medium · Level 04 Non-Linear Data Structures

Next Lower and Next Higher Ticket Number

binary search tree · predecessor · successor

A ticket office keeps issued ticket numbers in a binary search tree with distinct values. Given a number val that is in the tree, return [pred, succ]: the largest stored number strictly smaller than val and the smallest stored number strictly larger than val. Use None when there is no such number.

Examples

        46
       /  \
     28    63
    /  \     \
  15   37    84
    \
     24

Input:  root = build_tree([46, 28, 63, 15, 37, None, 84, None, 24]), val = 37
Output: [28, 46]

Input:  root = build_tree([46, 28, 63, 15, 37, None, 84, None, 24]), val = 15
Output: [None, 24]

Constraints

  • 1 <= number of nodes <= 3000
  • All values are distinct integers and val is present
  • O(h) time, without listing all values

Goals

  • Find the inorder predecessor and successor of a stored value in O(h)
  • Handle values at the ends of the order
Starting Python…