Find the closest element in Binary Search Tree
Given a binary search tree and a target node K. The task is to find the node with minimum absolute difference with given target value K.

Become a success story instead of just reading about them. Prepare for coding interviews at Amazon and other top product-based companies with our Amazon Test Series. Includes topic-wise practice questions on all important DSA topics along with 10 practice contests of 2 hours each. Designed by industry experts that will surely help you practice and sharpen your programming skills. Wait no more, start your preparation today!
Examples:
// For above binary search tree Input : k = 4 Output : 4 Input : k = 18 Output : 17 Input : k = 12 Output : 9
A simple solution for this problem is to store 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 in linear time.
An efficient solution for this problem is to take advantage of characteristics of BST. Here is the algorithm to solve this problem :
- If target value K is present in given BST, then it’s the node having minimum absolute difference.
- If target value K is less than the value of current node then move to the left child.
- If target value K is greater than the value of current node then move to the right child.
C++
// Recursive C++ program to find key closest to k// in given Binary Search Tree.#include<bits/stdc++.h>usingnamespacestd;/* A binary tree node has key, pointer to left childand a pointer to right child */structNode{intkey;structNode* left, *right;};/* Utility that allocates a new node with thegiven key and NULL left and right pointers. */structNode* newnode(intkey){structNode* node =new(structNode);node->key = key;node->left = node->right = NULL;return(node);}// Function to find node with minimum absolute// difference with given K// min_diff --> minimum difference till now// min_diff_key --> node having minimum absolute// difference with KvoidmaxDiffUtil(structNode *ptr,intk,int&min;_diff,int&min;_diff_key){if(ptr == NULL)return;// If k itself is presentif(ptr->key == k){min_diff_key = k;return;}// update min_diff and min_diff_key by checking// current node valueif(min_diff >abs(ptr->key - k)){min_diff =abs(ptr->key - k);min_diff_key = ptr->key;}// if k is less than ptr->key then move in// left subtree else in right subtreeif(k < ptr->key)maxDiffUtil(ptr->left, k, min_diff, min_diff_key);elsemaxDiffUtil(ptr->right, k, min_diff, min_diff_key);}// Wrapper over maxDiffUtil()intmaxDiff(Node *root,intk){// Initialize minimum differenceintmin_diff = INT_MAX, min_diff_key = -1;// Find value of min_diff_key (Closest key// in tree with k)maxDiffUtil(root, k, min_diff, min_diff_key);returnmin_diff_key;}// Driver program to run the caseintmain(){structNode *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 << maxDiff(root, k);return0;}Java
// Recursive Java program to find key closest to k// in given Binary Search Tree.classsolution{staticintmin_diff, min_diff_key;/* A binary tree node has key, pointer to left childand a pointer to right child */staticclassNode{intkey;Node left, right;};/* Utility that allocates a new node with thegiven key and null left and right pointers. */staticNode newnode(intkey){Node node =newNode();node.key = key;node.left = node.right =null;return(node);}// Function to find node with minimum absolute// difference with given K// min_diff -. minimum difference till now// min_diff_key -. node having minimum absolute// difference with KstaticvoidmaxDiffUtil(Node ptr,intk){if(ptr ==null)return;// If k itself is presentif(ptr.key == k){min_diff_key = k;return;}// update min_diff and min_diff_key by checking// current node valueif(min_diff > Math.abs(ptr.key - k)){min_diff = Math.abs(ptr.key - k);min_diff_key = ptr.key;}// if k is less than ptr.key then move in// left subtree else in right subtreeif(k < ptr.key)maxDiffUtil(ptr.left, k);elsemaxDiffUtil(ptr.right, k);}// Wrapper over maxDiffUtil()staticintmaxDiff(Node root,intk){// Initialize minimum differencemin_diff =999999999; min_diff_key = -1;// Find value of min_diff_key (Closest key// in tree with k)maxDiffUtil(root, k);returnmin_diff_key;}// Driver program to run the casepublicstaticvoidmain(String args[]){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;System.out.println( maxDiff(root, k));}}//contributed by Arnab KunduPython3
# Recursive Python program to find key# closest to k in given Binary Search Tree.# Utility that allocates a new node with the# given key and NULL left and right pointers.classnewnode:# Constructor to create a new nodedef__init__(self, data):self.key=dataself.left=Noneself.right=None# Function to find node with minimum# absolute difference with given K# min_diff --> minimum difference till now# min_diff_key --> node having minimum absolute# difference with KdefmaxDiffUtil(ptr, k, min_diff, min_diff_key):ifptr==None:return# If k itself is presentifptr.key==k:min_diff_key[0]=kreturn# update min_diff and min_diff_key by# checking current node valueifmin_diff >abs(ptr.key-k):min_diff=abs(ptr.key-k)min_diff_key[0]=ptr.key# if k is less than ptr->key then move# in left subtree else in right subtreeifk < ptr.key:maxDiffUtil(ptr.left, k, min_diff,min_diff_key)else:maxDiffUtil(ptr.right, k, min_diff,min_diff_key)# Wrapper over maxDiffUtil()defmaxDiff(root, k):# Initialize minimum differencemin_diff, min_diff_key=999999999999, [-1]# Find value of min_diff_key (Closest# key in tree with k)maxDiffUtil(root, k, min_diff, min_diff_key)returnmin_diff_key[0]# Driver Codeif__name__=='__main__':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)k=18print(maxDiff(root, k))# This code is contributed by PranchalKC#
usingSystem;// Recursive C# program to find key closest to k// in given Binary Search Tree.publicclasssolution{publicstaticintmin_diff, min_diff_key;/* A binary tree node has key, pointer to left childand a pointer to right child */publicclassNode{publicintkey;publicNode left, right;}/* Utility that allocates a new node with thegiven key and null left and right pointers. */publicstaticNode newnode(intkey){Node node =newNode();node.key = key;node.left = node.right =null;return(node);}// Function to find node with minimum absolute// difference with given K// min_diff -. minimum difference till now// min_diff_key -. node having minimum absolute// difference with KpublicstaticvoidmaxDiffUtil(Node ptr,intk){if(ptr ==null){return;}// If k itself is presentif(ptr.key == k){min_diff_key = k;return;}// update min_diff and min_diff_key by checking// current node valueif(min_diff > Math.Abs(ptr.key - k)){min_diff = Math.Abs(ptr.key - k);min_diff_key = ptr.key;}// if k is less than ptr.key then move in// left subtree else in right subtreeif(k < ptr.key){maxDiffUtil(ptr.left, k);}else{maxDiffUtil(ptr.right, k);}}// Wrapper over maxDiffUtil()publicstaticintmaxDiff(Node root,intk){// Initialize minimum differencemin_diff = 999999999;min_diff_key = -1;// Find value of min_diff_key (Closest key// in tree with k)maxDiffUtil(root, k);returnmin_diff_key;}// Driver program to run the casepublicstaticvoidMain(string[] args){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;Console.WriteLine(maxDiff(root, k));}}// This code is contributed by Shrikant13
Output:17
Time complexity : O(h) where h is height of given Binary Search Tree.
Reference :
http://stackoverflow.com/questions/6209325/how-to-find-the-closest-element-to-a-given-key-value-in-a-binary-search-tree
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



