Find the Closest Element in BST
https://practice.geeksforgeeks.org/problems/find-the-closest-element-in-bst/1/
Input:
10
/ \
2 11
/ \
1 5
/ \
3 6
\
4
K = 13
Output: 2
Explanation: K=13. The node that has
value nearest to K is 11. so the answer
is 2class Solution
{
public:
void helper(Node *root, int &mn_dif, int &k)
{
if (root = NULL)
return;
mn_dif = min(mn_dif, abs(root->data - k));
if (root->data > k)
helper(root->left, mn_dif, k);
else if (root->data < k)
helper(root->right, mn_dif, k);
else
return;
}
int minDiff(Node *root, int K)
{
int mn_dif = INT_MAX;
helper(root, mn_dif, K);
return mn_dif;
}
};
Comments
Post a Comment