Skip to problem
←

Minimum Absolute Difference in BST

Easy 0 attempts

Given the root of a binary search tree containing at least two nodes, return the smallest absolute difference between values of any two distinct nodes.

The chosen nodes do not have to be directly connected. This asks for a numerical difference, not the number of edges between nodes. For the BST [10,2,20,null,9], values 9 and 10 give the minimum difference 1, even though their nodes are not parent and child.

Function contract

Implement getMinimumDifference(root). Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.

Output: Return the smallest absolute value difference between two distinct nodes, not a node pair or their distance in the tree.

Example 1

Input
root = [4,2,6,1,3]
Output
1

Example 2

Input
root = [10,5,20]
Output
5
Constraints
  • 2 <= number of nodes <= 10^4
  • 0 <= Node.val <= 10^5
  • The tree is a strict BST: all left-subtree values are smaller and all right-subtree values are larger

Iterative Inorder

The closest pair in a sorted sequence must be adjacent. Track the preceding inorder value and the smallest gap.

javascript
function getMinimumDifference(root) {
  const stack=[];let current=root,previous=-Infinity,best=Infinity;
  while(current||stack.length) {
    while(current){stack.push(current);current=current.left;}
    current=stack.pop();best=Math.min(best,current.val-previous);previous=current.val;current=current.right;
  }
  return best;
}

Time: O(n) | Space: O(h) auxiliary space, excluding output

Loading discussion…

Saved in this browser only. Private to you.

JavaScript