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 =
What the first answer said, and here is the logic behind why it cannot get better than O(log n). You are looking for the largest number less than K. This is quite close to calling BST-search/get .
Although your original algorithm looks quite good, I think this would be faster:
int findNum (node root, int K) {
if(root == null) return -1;
if(K > root.val) {
if(root.right != null) return findNum(root.right, K);
else return root.val;
}
return findNum(root.left, K); //look in left subtree
}