Find the smallest difference between any two node values in a binary search tree
Company: HashiCorp
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Other
Overview: Given the root of a binary search tree, return the smallest absolute difference between the values of any two different nodes. The problem tests tree traversal, use of the BST ordering property, and linear-time reasoning for trees with up to ten thousand nodes.
Constraints
- The number of nodes in the tree is in the range [2, 10^4].
- 0 <= Node.val <= 10^5
- The tree is a valid BST: every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger, so all values are distinct.
- root is the level-order list of the tree with None marking a missing child; None appears only for missing children of present nodes and trailing None entries are omitted, so the list has at most 2 * 10^4 - 1 entries.
- The answer is between 1 and 10^5 and fits in a 32-bit signed integer.
Examples
Input: ([4, 2, 6, 1, 3],)
Expected Output: 1
Explanation: Source example 1: sorted values 1, 2, 3, 4, 6, and three neighboring pairs tie at 1.
Input: ([1, 0, 48, None, None, 12, 49],)
Expected Output: 1
Explanation: Source example 2: node 0 has two None children listed; sorted gaps 1, 11, 36, 1, so the tie at 1 includes the value 0.
Hints
- In Example 2 the closest values, 17 and 20, are not parent and child, so comparing each node only with its own children can miss the answer.
- Picture the node values written from smallest to largest. Which pairs in that list could hold the smallest difference?
- A tree with 10^4 nodes can be a single chain 10^4 levels deep, so plan for that depth.