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

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

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

         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…