VOOZH about

URL: https://www.geeksforgeeks.org/dsa/pair-with-minimum-absolute-difference-bst/

⇱ Minimum Difference Pair in BST - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum Difference Pair in BST

Last Updated : 7 May, 2026

Given a binary search tree of size n > 1, the task is to find the minimum absolute difference between any two nodes.

Examples:

Input:

👁 420046990

Output: 10
Explanation: There are no two nodes whose absolute difference is smaller than 10.

Input:

👁 2056957925

Output: 20
Explanation: There are no two nodes whose absolute difference is smaller than 20.

Using Inorder Traversal (BST Property) – O(n) Time and O(n) Space

The idea is to take advantage of the Binary Search Tree property where inorder traversal gives values in sorted order. Once the values are sorted, the minimum absolute difference will always be found between adjacent. So instead of comparing all pairs, we only check consecutive elements, which significantly reduces the time complexity.

  • Perform inorder traversal to store node values in sorted order
  • Traverse the sorted list and compute difference between adjacent elements
  • Track the minimum difference while iterating
  • Return the minimum difference obtained

Output
1

Using Inorder Traversal (Without Extra Space) – O(n) Time and O(h) Space

The idea is to use inorder traversal and keep track of the previously visited node during traversal. Since the values are visited in sorted order, the minimum difference will always occur between consecutive nodes.

  • Perform inorder traversal and maintain a pointer to the previously visited node
  • At each node, compute the difference with the previous node
  • Update the minimum difference accordingly
  • Continue traversal and return the final minimum difference



Output
1
Comment
Article Tags:
Article Tags: