I made nearest lower bound when I gave some integer in Binary Search Tree
def lowerBound(x : Int) : Int = {
var t = root
var result : Int = 0
while(t.key != x) {
if(x == t.key) {
result = t.left.key
}
else{
if(x < t.key) {
t = t.left
if(t == null) {
throw new NoSuchElementException
}
else {
result = t.key
}
}
else {
t = t.right
}
}
}
result
}
I have made like that. but it doesn’t print any result. T T….
is any counter example in my algorithm?
if there {2, 3, 5, 7 ,8, 10, 99}
lowerBound(6) is 5.
Homework?
Just a few pointers then:
t.key == x, so you cannot return successfully unless x is in the tree. Sounds wrong.Also