Here's the solution:
answer := 0
function dfs(u, parent, consecutive_cats):
if has_cat[u]:
consecutive_cats := consecutive_cats + 1
else:
consecutive_cats := 0
if consecutive_cats > m:
return
is_leaf := true
for each neighbor v of u:
if v != parent:
is_leaf := false
dfs(v, u, consecutive_cats)
if is_leaf:
answer := answer + 1
dfs(1, -1, 0)
print(answer)
Start from vertex with no parent and zero consecutive cats. If a cat appears, increment the streak. If not, reset to zero. Stop exploring if the streak exceeds . At leaves, increment the answer.
Time: . Space: for the recursion stack.