Your code gives WA as it does not stop on the path to one of the leaf nodes even after having greater than m consecutive vertices with cats,it refreshes the value of variable val to 0 on the same path and counts those leaf nodes as well.Example test case would be: Input : 4 1 1 1 0 0 1 2 2 3 3 4 Output : 0 (but your code gives output as 1) You can use a return statement to return from the path where greater than m consecutive vertices have cats.