The idea is to traverse every node of the Binary Search Tree (BST) and calculate the absolute difference between the current node's value and k. During the traversal, recursively compute the minimum difference for the left and right subtrees, and return the smallest among the current node, left subtree, and right subtree. Since every node is visited exactly once, the minimum absolute difference with k is obtained.
C++
#include<iostream>#include<climits>#include<cmath>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(){// Create the BST// 10// / \ // 2 11// / \ // 1 5// / \ // 3 6// \ // 4Node*root=newNode(10);root->left=newNode(2);root->right=newNode(11);root->left->left=newNode(1);root->left->right=newNode(5);root->left->right->left=newNode(3);root->left->right->right=newNode(6);root->left->right->left->right=newNode(4);intk=13;cout<<minDiff(root,k);return0;}
Java
// Structure of a tree nodeclassNode{intdata;Nodeleft;Noderight;Node(intval){data=val;left=right=null;}}classGFG{// 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){// Create the BST// 10// / \// 2 11// / \// 1 5// / \// 3 6// \// 4Noderoot=newNode(10);root.left=newNode(2);root.right=newNode(11);root.left.left=newNode(1);root.left.right=newNode(5);root.left.right.left=newNode(3);root.left.right.right=newNode(6);root.left.right.left.right=newNode(4);intk=13;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__":# Create the BST# 10# / \# 2 11# / \# 1 5# / \# 3 6# \# 4root=Node(10)root.left=Node(2)root.right=Node(11)root.left.left=Node(1)root.left.right=Node(5)root.left.right.left=Node(3)root.left.right.right=Node(6)root.left.right.left.right=Node(4)k=13print(minDiff(root,k))
C#
usingSystem;// Structure of a tree nodeclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}classGFG{// 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)));}staticvoidMain(){// Create the BST// 10// / \// 2 11// / \// 1 5// / \// 3 6// \// 4Noderoot=newNode(10);root.left=newNode(2);root.right=newNode(11);root.left.left=newNode(1);root.left.right=newNode(5);root.left.right.left=newNode(3);root.left.right.right=newNode(6);root.left.right.left.right=newNode(4);intk=13;Console.WriteLine(minDiff(root,k));}}
JavaScript
// Structure of a tree nodeclassNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Function to find least absolute differencefunctionminDiff(root,k){if(root===null)returnNumber.MAX_SAFE_INTEGER;// 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)));}// Driver code// Create the BST// 10// / \// 2 11// / \// 1 5// / \// 3 6// \// 4letroot=newNode(10);root.left=newNode(2);root.right=newNode(11);root.left.left=newNode(1);root.left.right=newNode(5);root.left.right.left=newNode(3);root.left.right.right=newNode(6);root.left.right.left.right=newNode(4);letk=13;console.log(minDiff(root,k));
Output
2
Using BST Property - O(h) Time and O(1) Space
The idea is to use the Binary Search Tree (BST) property to avoid visiting every node. While traversing the tree, keep track of the minimum absolute difference found so far. If the current node value is greater than k, move to the left subtree; otherwise, move to the right subtree, as it may contain a value closer to k.
Initialize a variable res with a very large value.
Start traversing the BST from the root.
At each node, update res with the minimum of its current value and abs(current->data - k).
If the current node value is greater than k, move to the left child.
Otherwise, move to the right child.
Continue until the current node becomes NULL.
Return res.
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;}intmain(){// Create the BST// 10// / \ // 2 11// / \ // 1 5// / \ // 3 6// \ // 4Node*root=newNode(10);root->left=newNode(2);root->right=newNode(11);root->left->left=newNode(1);root->left->right=newNode(5);root->left->right->left=newNode(3);root->left->right->right=newNode(6);root->left->right->left->right=newNode(4);intk=13;cout<<minDiff(root,k);return0;}
Java
classNode{intdata;Nodeleft;Noderight;Node(intx){data=x;left=right=null;}}classGFG{// 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){// Create the BST// 10// / \// 2 11// / \// 1 5// / \// 3 6// \// 4Noderoot=newNode(10);root.left=newNode(2);root.right=newNode(11);root.left.left=newNode(1);root.left.right=newNode(5);root.left.right.left=newNode(3);root.left.right.right=newNode(6);root.left.right.left.right=newNode(4);intk=13;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.rightreturnresif__name__=="__main__":# Create the BST# 10# / \# 2 11# / \# 1 5# / \# 3 6# \# 4root=Node(10)root.left=Node(2)root.right=Node(11)root.left.left=Node(1)root.left.right=Node(5)root.left.right.left=Node(3)root.left.right.right=Node(6)root.left.right.left.right=Node(4)k=13print(minDiff(root,k))
C#
usingSystem;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}classGFG{// 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(){// Create the BST// 10// / \// 2 11// / \// 1 5// / \// 3 6// \// 4Noderoot=newNode(10);root.left=newNode(2);root.right=newNode(11);root.left.left=newNode(1);root.left.right=newNode(5);root.left.right.left=newNode(3);root.left.right.right=newNode(6);root.left.right.left.right=newNode(4);intk=13;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 code// Create the BST// 10// / \// 2 11// / \// 1 5// / \// 3 6// \// 4letroot=newNode(10);root.left=newNode(2);root.right=newNode(11);root.left.left=newNode(1);root.left.right=newNode(5);root.left.right.left=newNode(3);root.left.right.right=newNode(6);root.left.right.left.right=newNode(4);letk=13;console.log(minDiff(root,k));