SPOJ MKTHNUM, Mergesort Tree help needed

Hello people,
I am stuck in MKTHNUM using mergesort tree in Java.
Java doesn’t have upper_bound / lower_bound method so I had to implement it on my own.
I have spent 2 days on debugging my code but I am unable to figure out what the hell is going wrong. . .
I even tried on pen and paper, and it gets messed up right before I am near the answer, (if I have to go on left branch, calculation suggests right branch and vice versa) :frowning: :((

here is the link of my code. . . (if I subtract 1 from returned value of KQuery, it gives correct output for sample cases but still wrong answer on 15th testcase in SPOJ)
please guide me. . . :frowning: