Minimum Distance Between BST Nodes Problem
Description
LeetCode Problem 783.
Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.
Example 1:
Input: root = [4,2,6,1,3]
Output: 1
Example 2:
Input: root = [1,0,48,null,null,12,49]
Output: 1
Constraints:
- The number of nodes in the tree is in the range [2, 100].
- 0 <= Node.val <= 10^5
Solution
Approach: In-Order Traversal
Comparing every pair of nodes takes O(n2) time. A BST gives us something better: an in-order traversal (left subtree, node, right subtree) visits the values in increasing order. In a sorted list, the smallest difference is always between two neighbors, because for a < b < c both b - a and c - b are at most c - a.
So traverse the tree in order and remember only the previously visited value:
- Keep
prev, the value visited just before the current node (none at the start), andbest, the smallest difference so far. - At each node, after its left subtree: if there is a
prev, updatebestwithnode.val - prev. Then setprev = node.valand continue into the right subtree.
The difference is never negative because the values arrive in increasing order, so no absolute value is needed. The mistake to avoid is comparing a node only with its children: the closest pair can be a node and a value deeper in one of its subtrees, like 4 and its grandchild 3 in [4,2,6,1,3].
Complexity: O(n) time and O(h) space for the recursion, where n is the number of nodes and h is the height of the tree.
class Solution:
def minDiffInBST(self, root: Optional[TreeNode]) -> int:
# An in-order traversal of a BST visits the values in increasing order,
# so the closest pair is always two consecutive values.
best = float("inf")
prev = None # the value visited just before the current node
def inorder(node: Optional[TreeNode]) -> None:
nonlocal best, prev
if node is None:
return
inorder(node.left)
if prev is not None:
best = min(best, node.val - prev)
prev = node.val
inorder(node.right)
inorder(root)
return best
Now write it from memory
Close the write-up and solve it yourself against the tests.