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;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode( int val)
{
this ->val = val;
left = NULL;
right = NULL;
}
};
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() {
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;
preorder(root,v);
int min_diff=INT_MAX;
int n=v.size();
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;
}
}
}
cout<< "the minimum difference is : " <<min_diff<<endl;
return 0;
}
|
Java
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode( int val)
{
this .val = val;
left = null ;
right = null ;
}
}
public class Main {
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)
{
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>();
preorder(root, v);
int min_diff = Integer.MAX_VALUE;
int n = v.size();
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;
}
}
}
System.out.println( "the minimum difference is : "
+ min_diff);
}
}
|
Python3
import sys
class TreeNode:
def __init__( self , val):
self .val = val
self .left = None
self .right = None
def preorder(root, v):
if root is None :
return
v.append(root.val)
preorder(root.left, v)
preorder(root.right, v)
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 )
v = []
preorder(root, v)
min_diff = sys.maxsize
n = len (v)
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
print ( "the minimum difference is : " , min_diff)
|
C#
using System;
using System.Collections.Generic;
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
{
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) {
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 >();
preorder(root, v);
int min_diff = int .MaxValue;
int n = v.Count;
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;
}
}
}
Console.WriteLine( "the minimum difference is : " + min_diff);
}
}
|
Javascript
class TreeNode {
constructor(val) {
this .val = val;
this .left = null ;
this .right = null ;
}
}
function preorder(root, v) {
if (root == null ) return ;
v.push(root.val);
preorder(root.left, v);
preorder(root.right, v);
}
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 = [];
preorder(root, v);
let min_diff = Number.MAX_SAFE_INTEGER;
let n = v.length;
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;
}
}
}
console.log( "the minimum difference is : " + min_diff);
|
Outputthe minimum difference is : 1
Complexity Analysis:
Time Complexity: O(n^2), For Traversing.
Auxiliary Space: O(n).
Approach: We know that the in-order traversal of a Binary Search Tree traverses it in sorted order. So, for every node, we will find its difference from the previous node in the in-order traversal of the tree. If this difference is smaller than the previous minimum difference, we will update the previous minimum difference. Following are the steps to follow:
- 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++
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
node* left;
node* right;
node( int data)
{
this ->data = data;
left = NULL;
right = NULL;
}
};
void inorder(node* curr, node*& prev, int & ans)
{
if (curr == NULL)
return ;
inorder(curr->left, prev, ans);
if (prev != NULL)
ans = min(curr->data - prev->data, ans);
prev = curr;
inorder(curr->right, prev, ans);
}
int minDiff(node* root)
{
node* prev = NULL;
int ans = INT_MAX;
inorder(root, prev, ans);
return ans;
}
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
import java.util.*;
class GFG
{
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;
static void inorder(node curr)
{
if (curr == null )
return ;
inorder(curr.left);
if (prev != null )
ans = Math.min(curr.data -
prev.data, ans);
prev = curr;
inorder(curr.right);
}
static int minDiff(node root)
{
prev = null ;
ans = Integer.MAX_VALUE;
inorder(root);
return ans;
}
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));
}
}
|
Python3
import math
class node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def inorder(curr, prev):
global ans
if (curr = = None ):
return
inorder(curr.left, prev)
if (prev ! = None ):
ans = min (curr.data - prev.data, ans)
prev = curr
inorder(curr.right, prev)
def minDiff(root):
prev = None
global ans
ans = math.inf
inorder(root, prev)
return ans
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#
using System;
class GFG
{
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;
static void inorder(node curr)
{
if (curr == null )
return ;
inorder(curr.left);
if (prev != null )
ans = Math.Min(curr.data -
prev.data, ans);
prev = curr;
inorder(curr.right);
}
static int minDiff(node root)
{
prev = null ;
ans = int .MaxValue;
inorder(root);
return ans;
}
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));
}
}
|
Javascript
<script>
class node
{
constructor(data)
{
this .data = data;
this .left = null ;
this .right = null ;
}
};
var prev = null ;
var ans =0;
function inorder(curr)
{
if (curr == null )
return ;
inorder(curr.left);
if (prev != null )
ans = Math.min(curr.data -
prev.data, ans);
prev = curr;
inorder(curr.right);
}
function minDiff(root)
{
prev = null ;
ans = 10000000000;
inorder(root);
return ans;
}
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));
</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.
Another Approach with O(N) Space Complexity:
C++
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
node* left;
node* right;
node( int data)
{
this ->data = data;
left = NULL;
right = NULL;
}
};
int absolute_diff(node* root, int target)
{
if (root == NULL)
return target;
if (root->left !=NULL)
{
int left = (root->data) - (root->left->data);
target = min(target, left);
}
if (root->right !=NULL)
{
int right = (root->right->data) - (root->data );
target = min(target, right);
}
int p = absolute_diff(root->left, target);
int q = absolute_diff(root->right, target);
return min(p, q);
}
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 << absolute_diff(root,INT_MAX);
return 0;
}
|
Java
class GFG {
static class TreeNode {
int data;
TreeNode left;
TreeNode right;
TreeNode( int data) { this .data = data; }
}
static int target = Integer.MAX_VALUE;
static int absolute_diff(TreeNode root, int target)
{
if (root == null )
return target;
if (root.left != null ) {
int left = root.data - root.left.data;
target = Math.min(target, left);
}
if (root.right != null ) {
int right = root.right.data - root.data;
target = Math.min(target, right);
}
int p = absolute_diff(root.left, target);
int q = absolute_diff(root.right, target);
return Math.min(p, q);
}
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(absolute_diff(root, target));
}
}
|
Python3
import math
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
target = math.inf
def absolute_diff(root, target):
if root is None :
return target
if root.left is not None :
left = root.data - root.left.data
target = min (target, left)
if root.right is not None :
right = root.right.data - root.data
target = min (target, right)
p = absolute_diff(root.left, target)
q = absolute_diff(root.right, target)
return min (p, q)
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 (absolute_diff(root, target))
|
C#
using System;
class GFG {
public class TreeNode {
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode( int data) { this .data = data; }
}
static int target = Int32.MaxValue;
static int absolute_diff(TreeNode root, int target)
{
if (root == null )
return target;
if (root.left != null ) {
int left = root.data - root.left.data;
target = Math.Min(target, left);
}
if (root.right != null ) {
int right = root.right.data - root.data;
target = Math.Min(target, right);
}
int p = absolute_diff(root.left, target);
int q = absolute_diff(root.right, target);
return Math.Min(p, q);
}
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(absolute_diff(root, target));
}
}
|
Javascript
<script>
class Node{
constructor(data){
this .data = data
this .left = null
this .right = null
}
}
let target = Number.MAX_VALUE
function absolute_diff(root, target){
if (root == null )
return target
if (root.left !== null ){
let left = root.data - root.left.data
target = Math.min(target, left)
}
if (root.right !== null ){
let right = root.right.data - root.data
target = Math.min(target, right)
}
let p = absolute_diff(root.left, target)
let q = absolute_diff(root.right, target)
return Math.min(p, q)
}
let 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(absolute_diff(root,target), "</br>" )
</script>
|
Time complexity: O(N)
Additional Space: O(N) due to recursion.
Another Simplest Approach with O(N) Extra Space:
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++
#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);
cout << getMinimumDifference(root);
return 0;
}
|
Java
import java.util.*;
class GFG {
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));
}
}
|
Python3
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 )
print (getMinimumDifference(root))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public class TreeNode
{
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode( int data)
{
this .data = data;
left = null ;
right = null ;
}
}
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));
}
}
|
Javascript
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);
console.log(getMinimumDifference(root));
|
Time complexity: O(N) As we go to all the nodes
Auxiliary Space: O(N) As the inorder vector is used then recursion stack space at worst.
As in the case of BST being skewed – recursion has N Function calls in the stack space.
Please Login to comment...