Trains do not connect all places in Vietnam - there's effectively one line that runs from Hanoi to HCMC along the coast for most of the route, and a couple of branch lines (to Lao Cai and Hai Phong) in the north.
You can see a map here (note that the route to Halong appears to be a bus) Note that not all trains call at all stops:
However, most of the places you mention are either accessible by train, or the train comes close to and you can transfer (Lao cai for Sapa, Da Nang for Hoi An).
However, Vietnamese trains are not very quick. For longer distances, flying is quicker and often comparable in price (although note that the cheaper Vietnamese carriers are notorious for cancelling underbooked flights). Bus services can be cheaper and competitive with the train on times as well (although considerably more dangerous).
The advantage that the trains can offer is overnight sleeper services, so that you can sleep on the train and still get a full day in at either end. Note that some people may find sleeping on the train much easier than others - these are not smooth European high-speed services - the trains sway considerably and will make stops during the night.