Open In App

Pair with minimum absolute difference in BST

Last Updated : 12 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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

Output
the 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:

  1. Perform inorder traversal of BST and store it in a array.
  2. The array is sorted, as it is BST.
  3. 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
  4. 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.

Output
1

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.

  1. Create a variable 'prev' to store the pointer to the previous node in in-order traversal.
  2. Create a variable 'ans' to store the minimum difference.
  3. 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> 

Output
1

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
Article Tags :

Similar Reads