FInding number of ancestors at given depth
We do a dfs starting from the root. we save the entry-time and exit time of each vertex. We build a list containing (height(v),entrytime(v)). Where entrytime is the time in the dfs where we first reached vertex v.

we now sort our list lexicographically (this takes time $\mathcal O(n\log(n))$ ) . Inside this order, the vertices at height $h$ that are ancestors of a vertex $v$ are the elements in the list that are between $(h,entrytime(v))$ and $(h,exittime(v))$.

So the problem is essentially reduced to the following:

Suppose we have an array of integers $a_1,a_2,\dots, a_n$, given $x$ and $p$ how can we find the number of elements in the range $a_1,a_2,\dots, a_p$ that are greater than $x$? (we just need $p-k$).

Various efficient solutions to this are discussed here: