The idea is to do Inorder traversal of given binary search tree in an auxiliary array and then by taking absolute difference of each element find the node having minimum absolute difference with given target value K.
C++
#include<iostream>#include<vector>#include<climits>usingnamespacestd;// Structure of a tree nodestructNode{intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};// Function to find least absolute differenceintminDiff(Node*root,intk){if(root==nullptr)returnINT_MAX;// Diff with rootintdiff=abs(root->data-k);// Return the minimum of three values: root// minimum in left and right subtreesreturnmin(diff,min(minDiff(root->left,k),minDiff(root->right,k)));}intmain(){Node*root=newNode(10);root->left=newNode(5);root->right=newNode(15);root->left->left=newNode(2);root->left->right=newNode(7);root->right->left=newNode(12);root->right->right=newNode(20);intk=9;cout<<minDiff(root,k);return0;}
Java
importjava.util.*;// Structure of a tree nodeclassNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}publicclassMain{// Function to find least absolute differencestaticintminDiff(Noderoot,intk){if(root==null)returnInteger.MAX_VALUE;// Diff with rootintdiff=Math.abs(root.data-k);// Return the minimum of three values: root// minimum in left and right subtreesreturnMath.min(diff,Math.min(minDiff(root.left,k),minDiff(root.right,k)));}publicstaticvoidmain(String[]args){Noderoot=newNode(10);root.left=newNode(5);root.right=newNode(15);root.left.left=newNode(2);root.left.right=newNode(7);root.right.left=newNode(12);root.right.right=newNode(20);intk=9;System.out.println(minDiff(root,k));}}
Python
# Structure of a tree nodeclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Function to find least absolute differencedefminDiff(root,k):ifrootisNone:returnfloat('inf')# Diff with rootdiff=abs(root.data-k)# Return the minimum of three values: root# minimum in left and right subtreesreturnmin(diff,min(minDiff(root.left,k),minDiff(root.right,k)))if__name__=='__main__':root=Node(10)root.left=Node(5)root.right=Node(15)root.left.left=Node(2)root.left.right=Node(7)root.right.left=Node(12)root.right.right=Node(20)k=9print(minDiff(root,k))
C#
usingSystem;// Structure of a tree nodepublicclassNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}publicclassProgram{// Function to find least absolute differencestaticintminDiff(Noderoot,intk){if(root==null)returnint.MaxValue;// Diff with rootintdiff=Math.Abs(root.data-k);// Return the minimum of three values: root// minimum in left and right subtreesreturnMath.Min(diff,Math.Min(minDiff(root.left,k),minDiff(root.right,k)));}publicstaticvoidMain(){Noderoot=newNode(10);root.left=newNode(5);root.right=newNode(15);root.left.left=newNode(2);root.left.right=newNode(7);root.right.left=newNode(12);root.right.right=newNode(20);intk=9;Console.WriteLine(minDiff(root,k));}}
JavaScript
// Structure of a tree nodefunctionNode(val){this.data=val;this.left=null;this.right=null;}// Function to find least absolute differencefunctionminDiff(root,k){if(root===null)returnNumber.MAX_VALUE;// Diff with rootletdiff=Math.abs(root.data-k);// Return the minimum of three values: root// minimum in left and right subtreesreturnMath.min(diff,Math.min(minDiff(root.left,k),minDiff(root.right,k)));}letroot=newNode(10);root.left=newNode(5);root.right=newNode(15);root.left.left=newNode(2);root.left.right=newNode(7);root.right.left=newNode(12);root.right.right=newNode(20);letk=9;console.log(minDiff(root,k));
Output
1
Using BST Property - O(h) Time and O(1) Space
The idea is to traverse the BST starting from the root and keep track of the closest value to k found so far. At each node, if the current value is closer to k, we update our closest. Depending on whether k is smaller or larger than the current node’s value, we move to the left or right subtree.
Step by Step implementation:
Start with the root node and initialize a variable to store the closest value.
Traverse the BST while the current node is not null.
Update the closest value if the current node’s value is closer to k.
Move to the left subtree if k is smaller, otherwise move to the right subtree.
Return the closest value after traversal completes.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Find minimum absolute difference with kintminDiff(Node*root,intk){intres=INT_MAX;Node*current=root;while(current!=nullptr){// Update answerres=min(res,abs(current->data-k));// Move according to BST propertyif(current->data>k){current=current->left;}else{current=current->right;}}returnres;}// Driver Codeintmain(){Node*root=newNode(9);root->left=newNode(4);root->right=newNode(17);root->left->left=newNode(3);root->left->right=newNode(6);root->left->right->left=newNode(5);root->left->right->right=newNode(7);root->right->right=newNode(22);root->right->right->left=newNode(20);intk=18;cout<<minDiff(root,k);return0;}
Java
importjava.util.Arrays;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}publicclassMain{// Find minimum absolute difference with kstaticintminDiff(Noderoot,intk){intres=Integer.MAX_VALUE;Nodecurrent=root;while(current!=null){// Update answerres=Math.min(res,Math.abs(current.data-k));// Move according to BST propertyif(current.data>k){current=current.left;}else{current=current.right;}}returnres;}publicstaticvoidmain(String[]args){Noderoot=newNode(9);root.left=newNode(4);root.right=newNode(17);root.left.left=newNode(3);root.left.right=newNode(6);root.left.right.left=newNode(5);root.left.right.right=newNode(7);root.right.right=newNode(22);root.right.right.left=newNode(20);intk=18;System.out.println(minDiff(root,k));}}
Python
classNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Find minimum absolute difference with kdefminDiff(root,k):res=float('inf')current=rootwhilecurrentisnotNone:# Update answerres=min(res,abs(current.data-k))# Move according to BST propertyifcurrent.data>k:current=current.leftelse:current=current.rightreturnres# Driver Coderoot=Node(9)root.left=Node(4)root.right=Node(17)root.left.left=Node(3)root.left.right=Node(6)root.left.right.left=Node(5)root.left.right.right=Node(7)root.right.right=Node(22)root.right.right.left=Node(20)k=18print(minDiff(root,k))
C#
usingSystem;publicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}classProgram{// Find minimum absolute difference with kstaticintminDiff(Noderoot,intk){intres=int.MaxValue;Nodecurrent=root;while(current!=null){// Update answerres=Math.Min(res,Math.Abs(current.data-k));// Move according to BST propertyif(current.data>k){current=current.left;}else{current=current.right;}}returnres;}staticvoidMain(string[]args){Noderoot=newNode(9);root.left=newNode(4);root.right=newNode(17);root.left.left=newNode(3);root.left.right=newNode(6);root.left.right.left=newNode(5);root.left.right.right=newNode(7);root.right.right=newNode(22);root.right.right.left=newNode(20);intk=18;Console.WriteLine(minDiff(root,k));}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Find minimum absolute difference with kfunctionminDiff(root,k){letres=Number.MAX_SAFE_INTEGER;letcurrent=root;while(current!==null){// Update answerres=Math.min(res,Math.abs(current.data-k));// Move according to BST propertyif(current.data>k){current=current.left;}else{current=current.right;}}returnres;}// Driver Codeletroot=newNode(9);root.left=newNode(4);root.right=newNode(17);root.left.left=newNode(3);root.left.right=newNode(6);root.left.right.left=newNode(5);root.left.right.right=newNode(7);root.right.right=newNode(22);root.right.right.left=newNode(20);letk=18;console.log(minDiff(root,k));
Output
1
Time Complexity: O(h),where h is the height of the BST, as we traverse only one path. Space Complexity: O(1), for the iterative approach, as no extra space is used.