Pair with minimum absolute difference in BST
Last Updated :
12 Jul, 2025
Given a binary search tree of size N > 1, the task is to find the minimum absolute difference between any two nodes.
Examples:
Input:
5
/ \
3 7
/ \ / \
2 4 6 8
Output: 1
Difference between all the consecutive nodes if sorted is 1.
Thus, the answer is 1.
Input:
1
\
6
Output: 5
Brute Force Using preorder:
Here in this approach we find the perorder of the bst then we traverse over it to find minimum difference.
C++
#include <bits/stdc++.h>
using namespace std;
//class for tree.
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int val)
{
this->val = val;
left = NULL;
right = NULL;
}
};
//preorder finder function.
void preorder(TreeNode* root,vector<int>&v){
if(root==NULL)return;
v.push_back(root->val);
preorder(root->left,v);
preorder(root->right,v);
}
int main() {
//BStree
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(3);
root->right = new TreeNode(7);
root->left->left = new TreeNode(2);
root->left->right = new TreeNode(4);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(8);
vector<int>v;
//call for preorder.
preorder(root,v);
int min_diff=INT_MAX;
int n=v.size();
//traversing and checking.
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
int x=abs(v[i]-v[j]);
if(min_diff>x){
min_diff=x;
}
}
}
//printing the output.
cout<<"the minimum difference is : "<<min_diff<<endl;
return 0;
//code by Sanket Gode.
}
Java
import java.util.*;
// class for tree.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val)
{
this.val = val;
left = null;
right = null;
}
}
public class Main { // preorder finder function.
public static void preorder(TreeNode root,
List<Integer> v)
{
if (root == null)
return;
v.add(root.val);
preorder(root.left, v);
preorder(root.right, v);
}
public static void main(String[] args)
{
// BSTree
TreeNode root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(7);
root.left.left = new TreeNode(2);
root.left.right = new TreeNode(4);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(8);
List<Integer> v = new ArrayList<Integer>();
// call for preorder.
preorder(root, v);
int min_diff = Integer.MAX_VALUE;
int n = v.size();
// traversing and checking.
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int x = Math.abs(v.get(i) - v.get(j));
if (min_diff > x) {
min_diff = x;
}
}
}
// printing the output.
System.out.println("the minimum difference is : "
+ min_diff);
}
}
Python
# Python implementation of the above C++ code
import sys
# Class for tree
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# Preorder finder function
def preorder(root, v):
if root is None:
return
v.append(root.val)
preorder(root.left, v)
preorder(root.right, v)
if __name__ == '__main__':
# BSTree
root = TreeNode(5)
root.left = TreeNode(3)
root.right = TreeNode(7)
root.left.left = TreeNode(2)
root.left.right = TreeNode(4)
root.right.left = TreeNode(6)
root.right.right = TreeNode(8)
v = []
# Call for preorder
preorder(root, v)
min_diff = sys.maxsize
n = len(v)
# Traversing and checking
for i in range(n):
for j in range(i+1, n):
x = abs(v[i]-v[j])
if min_diff > x:
min_diff = x
# Printing the output
print("the minimum difference is : ", min_diff)
# This code is contributed by adityashatmfh
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
// class for tree.
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
this.val = val;
left = null;
right = null;
}
}
public class GFG
{
// preorder finder function.
public static void preorder(TreeNode root, List<int> v) {
if (root == null)
return;
v.Add(root.val);
preorder(root.left, v);
preorder(root.right, v);
}
public static void Main(string[] args) {
// BSTree
TreeNode root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(7);
root.left.left = new TreeNode(2);
root.left.right = new TreeNode(4);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(8);
List<int> v = new List<int>();
// call for preorder.
preorder(root, v);
int min_diff = int.MaxValue;
int n = v.Count;
// traversing and checking.
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int x = Math.Abs(v[i] - v[j]);
if (min_diff > x) {
min_diff = x;
}
}
}
// printing the output.
Console.WriteLine("the minimum difference is : " + min_diff);
}
}
// This code is contributed by rishabmalhdijo
JavaScript
//class for tree.
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
//preorder finder function.
function preorder(root, v) {
if (root == null) return;
v.push(root.val);
preorder(root.left, v);
preorder(root.right, v);
}
//BStree
let root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(7);
root.left.left = new TreeNode(2);
root.left.right = new TreeNode(4);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(8);
let v = [];
//call for preorder.
preorder(root, v);
let min_diff = Number.MAX_SAFE_INTEGER;
let n = v.length;
//traversing and checking.
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
let x = Math.abs(v[i] - v[j]);
if (min_diff > x) {
min_diff = x;
}
}
}
//printing the output.
console.log("the minimum difference is : " + min_diff);
// This code is contributed by sarojmcy2e
Outputthe minimum difference is : 1
Complexity Analysis:
Time Complexity: O(n^2), For Traversing.
Auxiliary Space: O(n).
A Better Approach (Inorder Traversal and Array)
Algorithm:
- Perform inorder traversal of BST and store it in a array.
- The array is sorted, as it is BST.
- Now just do :
- Arr[i+1] - Arr[i]
- Minimize the above value. i.e. Find the min most difference
- No need to use abs() as array is sorted. i+1 element is always >= i element
- Return the min value.
C++
// Code of above algo
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int val)
{
this->val = val;
left = NULL;
right = NULL;
}
};
void inorder(vector<int>& inord, TreeNode* root)
{
if (root == NULL)
return;
inorder(inord, root->left);
inord.push_back(root->val);
inorder(inord, root->right);
}
int getMinimumDifference(TreeNode* root)
{
vector<int> inord;
inorder(inord, root);
int mini = INT_MAX;
int N = inord.size();
for (int i = 0; i < N - 1; i++) {
mini = min(mini, inord[i + 1] - inord[i]);
}
return mini;
}
int main()
{
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(3);
root->right = new TreeNode(7);
root->left->left = new TreeNode(2);
root->left->right = new TreeNode(4);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(8);
// Function call
cout << getMinimumDifference(root);
return 0;
}
Java
// Java implementation of above approach
import java.util.*;
class GFG {
// Node of the binary tree
static class TreeNode {
int data;
TreeNode left;
TreeNode right;
TreeNode(int data)
{
this.data = data;
left = null;
right = null;
}
};
static void inorder(ArrayList<Integer> inord,
TreeNode root)
{
if (root == null)
return;
inorder(inord, root.left);
inord.add(root.data);
inorder(inord, root.right);
}
static int getMinimumDifference(TreeNode root)
{
ArrayList<Integer> inord = new ArrayList<>();
inorder(inord, root);
int mini = Integer.MAX_VALUE;
int N = inord.size();
for (int i = 0; i < N - 1; i++) {
mini = Math.min(mini, inord.get(i + 1)
- inord.get(i));
}
return mini;
}
public static void main(String[] args)
{
TreeNode root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(7);
root.left.left = new TreeNode(2);
root.left.right = new TreeNode(4);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(8);
System.out.println(getMinimumDifference(root));
}
}
// This code is contributed by karandeep1234.
Python
# Code of above algo
from typing import List, Tuple
class TreeNode:
def __init__(self, val: int):
self.val = val
self.left = None
self.right = None
def inorder(inord: List[int], root: TreeNode) -> None:
if root is None:
return
inorder(inord, root.left)
inord.append(root.val)
inorder(inord, root.right)
def getMinimumDifference(root: TreeNode) -> int:
inord = []
inorder(inord, root)
mini = float("inf")
N = len(inord)
for i in range(N - 1):
mini = min(mini, inord[i + 1] - inord[i])
return mini
if __name__ == "__main__":
root = TreeNode(5)
root.left = TreeNode(3)
root.right = TreeNode(7)
root.left.left = TreeNode(2)
root.left.right = TreeNode(4)
root.right.left = TreeNode(6)
root.right.right = TreeNode(8)
# Function call
print(getMinimumDifference(root))
#This code is contributed by Potta Lokesh
C#
//C# code for the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Node of the binary tree
public class TreeNode
{
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode(int data)
{
this.data = data;
left = null;
right = null;
}
}
// Function to perform inorder traversal of the tree
public static void inorder(List<int> inord, TreeNode root)
{
if (root == null)
return;
inorder(inord, root.left);
inord.Add(root.data);
inorder(inord, root.right);
}
public static int getMinimumDifference(TreeNode root)
{
List<int> inord = new List<int>();
inorder(inord, root);
int mini = int.MaxValue;
int N = inord.Count;
for (int i = 0; i < N - 1; i++)
{
mini = Math.Min(mini, inord[i + 1] - inord[i]);
}
return mini;
}
public static void Main(string[] args)
{
TreeNode root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(7);
root.left.left = new TreeNode(2);
root.left.right = new TreeNode(4);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(8);
Console.WriteLine(getMinimumDifference(root));
}
}
//This code is contributed by Potta Lokesh
JavaScript
// JavaScript implementation of above approach
class TreeNode {
constructor(val)
{
this.val = val;
this.left = null;
this.right = null;
}
};
function inorder(inord, root)
{
if (root == null)
return;
inorder(inord, root.left);
inord.push(root.val);
inorder(inord, root.right);
}
function getMinimumDifference(root)
{
let inord=[];
inorder(inord, root);
let mini = Number.MAX_VALUE;
let N = inord.length;
for (let i = 0; i < N - 1; i++) {
mini = Math.min(mini, inord[i + 1] - inord[i]);
}
return mini;
}
let root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(7);
root.left.left = new TreeNode(2);
root.left.right = new TreeNode(4);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(8);
// Function call
console.log(getMinimumDifference(root));
// This code is contributed by garg28harsh.
Time complexity: O(N) As we go to all the nodes
Auxiliary Space: O(N) An extra array is used to store inorder traversal
Optimized Approach (Only Inorder)
This is mainly an optimization over the previous approach. We can avoid the use of extra array and find the minimum difference with inorder traversal only.
- Create a variable 'prev' to store the pointer to the previous node in in-order traversal.
- Create a variable 'ans' to store the minimum difference.
- For every node in the in-order traversal, compare its absolute difference with the previous node and update the minimum absolute difference found so far.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Node of the binary tree
struct node {
int data;
node* left;
node* right;
node(int data)
{
this->data = data;
left = NULL;
right = NULL;
}
};
// Function for in-order traversal of the tree
void inorder(node* curr, node*& prev, int& ans)
{
// Base-case
if (curr == NULL)
return;
// Calling in-order on the left sub-tree
inorder(curr->left, prev, ans);
if (prev != NULL)
ans = min(curr->data - prev->data, ans);
prev = curr;
// Calling in-order on the right sub-tree
inorder(curr->right, prev, ans);
}
// Function to return the minimum
// difference between any two nodes
// of the given binary search tree
int minDiff(node* root)
{
// Pointer to previous node in the
// in-order traversal of the BST
node* prev = NULL;
// To store the final ans
int ans = INT_MAX;
// Call in-order for the BST
inorder(root, prev, ans);
// Returning the final answer
return ans;
}
// Driver code
int main()
{
node* root = new node(5);
root->left = new node(3);
root->right = new node(7);
root->left->left = new node(2);
root->left->right = new node(4);
root->right->left = new node(6);
root->right->right = new node(8);
cout << minDiff(root);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
// Node of the binary tree
static class node
{
int data;
node left;
node right;
node(int data)
{
this.data = data;
left = null;
right = null;
}
};
static node prev;
static int ans;
// Function for in-order traversal of the tree
static void inorder(node curr)
{
// Base-case
if (curr == null)
return;
// Calling in-order on the left sub-tree
inorder(curr.left);
if (prev != null)
ans = Math.min(curr.data -
prev.data, ans);
prev = curr;
// Calling in-order on the right sub-tree
inorder(curr.right);
}
// Function to return the minimum
// difference between any two nodes
// of the given binary search tree
static int minDiff(node root)
{
// Pointer to previous node in the
// in-order traversal of the BST
prev = null;
// To store the final ans
ans = Integer.MAX_VALUE;
// Call in-order for the BST
inorder(root);
// Returning the final answer
return ans;
}
// Driver code
public static void main(String[] args)
{
node root = new node(5);
root.left = new node(3);
root.right = new node(7);
root.left.left = new node(2);
root.left.right = new node(4);
root.right.left = new node(6);
root.right.right = new node(8);
System.out.println(minDiff(root));
}
}
// This code is contributed by 29AjayKumar
Python
# Python 3 implementation of the approach
import math
# Node of the binary tree
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function for in-order traversal of the tree
def inorder(curr, prev):
global ans
# Base-case
if (curr == None):
return
# Calling in-order on the left sub-tree
inorder(curr.left, prev)
if (prev != None):
ans = min(curr.data - prev.data, ans)
prev = curr
# Calling in-order on the right sub-tree
inorder(curr.right, prev)
# Function to return the minimum
# difference between any two nodes
# of the given binary search tree
def minDiff(root):
# Pointer to previous node in the
# in-order traversal of the BST
prev = None
# To store the final ans
global ans
ans = math.inf
# Call in-order for the BST
inorder(root, prev)
# Returning the final answer
return ans
# Driver code
if __name__ == '__main__':
root = node(5)
root.left = node(3)
root.right = node(7)
root.left.left = node(2)
root.left.right = node(4)
root.right.left = node(6)
root.right.right = node(8)
print(minDiff(root))
C#
// C# implementation of the approach
using System;
class GFG
{
// Node of the binary tree
public class node
{
public int data;
public node left;
public node right;
public node(int data)
{
this.data = data;
left = null;
right = null;
}
};
static node prev;
static int ans;
// Function for in-order traversal of the tree
static void inorder(node curr)
{
// Base-case
if (curr == null)
return;
// Calling in-order on the left sub-tree
inorder(curr.left);
if (prev != null)
ans = Math.Min(curr.data -
prev.data, ans);
prev = curr;
// Calling in-order on the right sub-tree
inorder(curr.right);
}
// Function to return the minimum
// difference between any two nodes
// of the given binary search tree
static int minDiff(node root)
{
// Pointer to previous node in the
// in-order traversal of the BST
prev = null;
// To store the final ans
ans = int.MaxValue;
// Call in-order for the BST
inorder(root);
// Returning the final answer
return ans;
}
// Driver code
public static void Main(String[] args)
{
node root = new node(5);
root.left = new node(3);
root.right = new node(7);
root.left.left = new node(2);
root.left.right = new node(4);
root.right.left = new node(6);
root.right.right = new node(8);
Console.WriteLine(minDiff(root));
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// Javascript implementation of the approach
// Node of the binary tree
class node
{
constructor(data)
{
this.data = data;
this.left = null;
this.right = null;
}
};
var prev = null;
var ans =0;
// Function for in-order traversal of the tree
function inorder(curr)
{
// Base-case
if (curr == null)
return;
// Calling in-order on the left sub-tree
inorder(curr.left);
if (prev != null)
ans = Math.min(curr.data -
prev.data, ans);
prev = curr;
// Calling in-order on the right sub-tree
inorder(curr.right);
}
// Function to return the minimum
// difference between any two nodes
// of the given binary search tree
function minDiff(root)
{
// Pointer to previous node in the
// in-order traversal of the BST
prev = null;
// To store the final ans
ans = 10000000000;
// Call in-order for the BST
inorder(root);
// Returning the final answer
return ans;
}
// Driver code
var root = new node(5);
root.left = new node(3);
root.right = new node(7);
root.left.left = new node(2);
root.left.right = new node(4);
root.right.left = new node(6);
root.right.right = new node(8);
document.write(minDiff(root));
// This code is contributed by noob2000
</script>
Time Complexity: O(N) where N is the number of nodes in the given BST.
Auxiliary Space: O(h) where h is the height of given BST due to recursion.
Minimum Absolute Difference In BST | DSA Problem
Similar Reads
Find a pair with sum N having minimum absolute difference Given an integer N, the task is to find a distinct pair of X and Y such that X + Y = N and abs(X - Y) is minimum. Examples: Input: N = 11Output: 5 6 Explanation:X = 5 and Y = 6 satisfy the given equation. Therefore, the minimum absolute value of abs(X - Y) = 1. Input: N = 12 Output: 5 7 Naive Approa
6 min read
Count of all pairs in an Array with minimum absolute difference Given an integer array arr[] of size N, the task is to count the total number of distinct pairs having minimum absolute difference. Examples: Input: arr[] = {4, 2, 1, 3} Output: 3 Explanation: The minimum absolute difference between the pairs {1, 2}, {2, 3}, {3, 4} is 1.Input: arr[] = {1, 3, 8, 10,
5 min read
Pair with minimum absolute difference after solving each query Given Q queries and an empty list. The queries can be of two types: addToList(x) : Add x to your list.removeFromList(x) : Remove x from your list.The task is, after each query, you have to print the minimum value of abs(list[i]-list[j]) where, 0<=i<=n, 0<=j<=n and i ? j and n is the tota
14 min read
Find the minimum absolute difference in two different BST's Given 2 Binary Search Trees, select one node from each tree such that their absolute difference is minimum possible. Assume each BST has at-least one node. Examples: Input : N1 = 7, N2 = 2 BST1 : 5 / \ 3 7 / \ / \ 2 4 6 8 BST2 : 11 \ 13 Output : 3 8 is largest number in the first BST and 11 is small
8 min read
Co-prime pair with given sum minimum difference Co-prime or mutually prime pairs are those pairs of numbers whose GCD is 1. Given a number n represent the number as the sum of a Co-prime pair (A, B) such that A - B is minimum. Examples : Input : 12 Output : 5 7 Possible co-prime pairs are (5, 7), (1, 11) but difference between 5 and 7 is minimum
5 min read
Sum of minimum absolute differences in an array Given an array of n distinct integers. The task is to find the sum of minimum absolute difference of each array element. For an element arr[i] present at index i in the array, its minimum absolute difference is calculated as: Min absolute difference (arr[i]) = min(abs(arr[i] - arr[j])), where 0 <
7 min read