It is possible to get from Bucharest to Sarajevo on train - likely requiring a rather roundabout route via Budapest, Hungary and Zagreb, Croatia or even Salzburg, Austria an thus easily taking as much as 48h.
A map of the railway lines in Europe may be found on the interrail website and their timetable/trip planner will provide connections and times.
Entering Bucharest and Sarajevo as start and end of your travel may or may not yield the optimum connections - do play around with adding stops in between to see if you can manually figure out a better solution than the one initially suggested by the site.
If you're happy to consider other means of transport (i.e. bus) and/or mixing means of transport, this may become much easier, using the Budapest to Sarajevo bus. See here for a useful site that allows comparisons of means of transport.