The problem. Given the root of a binary search tree with at least two nodes, return the minimum absolute difference between the values of any two different nodes.
root = [4, 2, 6, 1, 3] -> 1
root = [1, 0, 48, null, null, 12, 49] -> 1 (48 and 49)
root = [10, 5, 20] -> 5If the values were in a sorted list, the closest pair would be adjacent — any value between two others is closer to each of them than they are to each other. A BST hands you that sorted list for free: its in-order walk. So walk in-order and compare each value with the one just before it.
function getMinimumDifference(root) { const values = []; const walk = (node) => { if (node === null) return; values.push(node.val); walk(node.left); walk(node.right); }; walk(root); let best = Infinity; for (let i = 0; i < values.length; i++) for (let j = i + 1; j < values.length; j++) best = Math.min(best, Math.abs(values[i] - values[j])); return best;}Time O(n²), space O(n). It works on any binary tree — it ignores the ordering completely.
In-order visits values in sorted order; only the gap to the previous value can be the new best.
function getMinimumDifference(root) { let prev = null; let best = Infinity; const inorder = (node) => { if (node === null) return; inorder(node.left); if (prev !== null) best = Math.min(best, node.val - prev); // sorted, so the gap is never negative prev = node.val; inorder(node.right); }; inorder(root); return best;}Time O(n), space O(h). Same answer as LeetCode 783 (Minimum Distance Between BST Nodes) — it's the same problem.