SPOJ - KQUERY

Can Someone please look at my code. I solved it using Segment tree and getting a TLE. I think this because the way i query. Problem KQUERY

Code -
import java.io.;
import java.util.
;

class Main {
    static StreamTokenizer st = new StreamTokenizer (new BufferedReader (new InputStreamReader (System.in)));
    static class sc {
        static int nextInt () throws IOException {
            st.nextToken();
            return (int)st.nval;
        }
    }

    static class Node {
        int min, max;

        Node (int val) {
            min = max = val;
        }

        Node (Node a, Node b) {
            min = Math.min (a.min, b.min);
            max = Math.max (a.max, b.max);
        }
    }

    static void build (int l, int r, int idx) {
        if (l == r) tree [idx] = new Node (ar[l]);
        else {
            int m = (l+r)/2;
            build (l, m, 2*idx);
            build (m+1, r, 2*idx+1);
            tree [idx] = new Node (tree[2*idx], tree[2*idx+1]);
        }
    }

    static int query (int l, int r, int low, int high, int idx, int k) {
        if (high < l || low > r) return 0;
        if (l <= low && high <= r) {
            if (tree[idx].min > k) return high-low+1;
            if (tree[idx].max <= k) return 0;
        }
        
        int mid = (low + high)/2;
        int left = query (l, r, low, mid, 2*idx, k);
        int right = query (l, r, mid+1, high, 2*idx+1, k);
        return left + right;
    }

    static int ar[];
    static Node tree [];

    public static void main(String[] args) throws Exception {
        int n = sc.nextInt();
        ar = new int [n];
        for (int i=0; i<n; i++) ar[i] = sc.nextInt();

        int size =1 ;
        while (size <= n) size *=2; size *= 2;

        tree = new Node [size];

        build(0, n-1, 1);

        int m = sc.nextInt();

        while (m-- > 0) {
            int l = sc.nextInt() - 1;
            int r = sc.nextInt() - 1;
            int k = sc.nextInt();
            System.out.println (query(l, r, 0, n-1, 1, k));
        }
    }
}