TLE IN QTREE 2

I AM CONSTANTLY GETING TLE IN QTREE 2 PROBLEM ON SPOJ CAN ANYONE SPECIFY WHY MY CODE IS SLOW
implementation detail:
i used hld as preprocess then i used segment tree to find lca
now to answer query of type 1 DIS U V i used traversing tree using hld method in logn^2 time(mot probably here it is giving tle) to answer query of type 2 again used hld traversal and tried to reach kth node in logn^2 time by finding the segment in which kth node lies… please check it i also checked with spojtoolkit taking an input as big but here its working absolutely fine but i dont know why it is not working on final submission…please look into it;
link to problem: https://www.spoj.com/problems/QTREE2/
link to my solution: https://ideone.com/1HCs4A