When. the train approaches you, the wavelength of the sound waves it emits are compressed, and therefore the whistle sounds higher.
But When the train is moving away, the wavelengths are extended, causing the whistle to sound lower. It's called the Doppler effect.