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

Closest Pair of Timestamps

binary search tree · inorder traversal

A log stores event timestamps in a binary search tree with distinct values. Return the smallest difference between any two timestamps. Return None if the tree has fewer than two nodes.

Examples

        50
       /  \
     30    70
    /  \     \
  20   40    80
    \
     25

Input:  root = build_tree([50, 30, 70, 20, 40, None, 80, None, 25])
Output: 5         (25 - 20)

         12
        /  \
       7    18
      / \   / \
     3   9 15  22
      \
       5

Input:  root = build_tree([12, 7, 18, 3, 9, 15, 22, None, 5])
Output: 2

Constraints

  • 0 <= number of nodes <= 3000
  • All values are distinct integers
  • O(n) time, O(h) extra space

Goals

  • Realise that the closest pair are neighbours in sorted order
  • Compare each value only with the previous one visited
Starting Python…