Usually, when a star dies, it will usually form a planetary nebula or supernova and most of this matter will reach the interstellar medium.
When it collapses due to some disturbance, a protoplanetary disk forms, it will cool off eventually. Once it is low enough temperature to form compounds, usually molecular hydrogen (H2) will form first. Here is something that may help you:
No, H2O cannot exist in stars, but H and O separately can. Hydrogen is the basic building material of the universe, created in the Big Bang. Oxygen is created by nuclear reactions in stars. If you put H and O together in the cold of space, you get H2O. There are enormous amounts of water in space. In fact, nearly all of the oxygen in space is in the form of water or carbon monoxide. Similarly, most the carbon and nitrogen in space are also in their most hydrogenated forms: methane (CH4) and ammonia (NH3).
Since water is H2O, it is likely to form because nebulae contain so much hydrogen and some oxygen. The Earth was most likely hit by comets and asteroids that contained water, and when our planet cooled off, we got our oceans.