Given a binary search tree and an integer K, i would like to find the largest element less than K.
In the below tree,
for K = 13, result = 12
for K = 10, result = 8
for K = 1 (or) 2, result = -1
10
5 12
2 8 11 14
I tried the below logic. But is there any better way to do this ?
int findNum(node* node, int K)
{
if(node == NULL)
{
return -1;
}
else if(K <= node->data)
{
return findNum(node->left,K);
}
else if(K > node->data)
{
int t = findNum(node->right,K);
return t > node->data ? t : node->data;
}
return -1;
}