Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Pair with minimum absolute difference in BST

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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);
    }
}

Python3




# 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).

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:  

  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

Python3




# 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.

Another Approach with O(N) Space Complexity:

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;
    }
};
 
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);
        }
         
    // Find the minimum in the left subtree
    int p = absolute_diff(root->left, target);
     
    // Find the minimum in the right subtree
    int q = absolute_diff(root->right, target);
    return min(p, q);
}
 
// 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 << absolute_diff(root,INT_MAX);
 
    return 0;
}
 
// This code is contributed by Arpit Jain

Java




// Java implementation of the approach
class GFG {
 
    // Node of the binary tree
    static class TreeNode {
        int data;
        TreeNode left;
        TreeNode right;
 
        TreeNode(int data) { this.data = data; }
    }
 
    static int target = Integer.MAX_VALUE;
 
    // Function to find the minimum absolute difference
    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);
        }
 
        // Find the minimum in the left subtree
        int p = absolute_diff(root.left, target);
       
        // Find the minimum in the right subtree
        int q = absolute_diff(root.right, target);
        return Math.min(p, q);
    }
 
    // Driver code
    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));
    }
}
 
// This code is contributed by Lovely Jain

Python3




# Python 3 implementation of the approach
 
# Node of the binary tree
import math
 
class Node:
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
 
# Set the target to infinity
target = math.inf
# Function to find the minimum absolute difference
 
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)
    # Find the minimum in the left subtree
    p = absolute_diff(root.left, target)
    # Find the minimum in the right subtree
    q = absolute_diff(root.right, target)
    return min(p, q)
 
 
# Driver code
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#




// C# implementation of the approach
using System;
 
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; }
    }
 
    static int target = Int32.MaxValue;
 
    // Function to find the minimum absolute difference
    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);
        }
 
        // Find the minimum in the left subtree
        int p = absolute_diff(root.left, target);
 
        // Find the minimum in the right subtree
        int q = absolute_diff(root.right, target);
        return Math.Min(p, q);
    }
 
    // Driver code
    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));
    }
}
 
// This code is contributed by karandeep1234

Javascript




<script>
 
//  JavaScript implementation of the approach
 
//  Node of the binary tree
class Node{
 
    //  Constructor to create a new node
    constructor(data){
        this.data = data
        this.left = null
        this.right = null
    }
}
 
// Set the target to infinity
let target = Number.MAX_VALUE
 
// Function to find the minimum absolute difference
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)
    }
    // Find the minimum in the left subtree
    let p = absolute_diff(root.left, target)
     
    // Find the minimum in the right subtree
    let q = absolute_diff(root.right, target)
    return Math.min(p, q)
}
 
// Driver code
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>")
 
// This code is contributed by shinjanpatra
 
</script>

Output

1

Time complexity: O(N) 
Additional Space: O(N) due to recursion.
 

Another Simplest Approach with O(N) Extra Space:

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.

Python3




# 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)  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.


My Personal Notes arrow_drop_up
Last Updated : 27 Mar, 2023
Like Article
Save Article
Similar Reads
Related Tutorials