The answer is natural selection.
In natural selection, genotype variations that will increase the chance of survival and reproduction of some organism are preserved and will be inherited. Red and green colors of butterflies increased the chance of their survival and reproduction, so these traits will pass to the next generation.