Query tree Optimization

I tried many times but am not able to find out the reason for TLE.

Question- https://www.spoj.com/problems/QTREE/
My solution- https://ideone.com/0VzhjU

I have used the concept of heavy light decomposition.
Plz help me in optimizing my code.

Did anyone find out the reason for TLE?