CodingNodes / Trees / Minimum Absolute Difference in BST System design Space play · ←→ step · R restart

Problem

Given the root of a binary search tree, return the smallest absolute difference between the values of any two different nodes.

The tree is given in level order, with null for a missing child.

Constraints

  • 2 ≤ number of nodes ≤ 10000
  • 0 ≤ Node.val ≤ 100000

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(h)

Time: The in-order walk visits every node exactly once, with constant work per node.

Space: The recursion is as deep as the tree is tall, h. That is log n for a balanced tree and n for a chain.

Walking a search tree in order, left then node then right, visits the values in increasing order. The two closest values must sit next to each other in that order, so only neighbours need comparing. Remember the previous value, and for each new one try new minus previous as the answer. Keep the smallest.