Recalculating the roots tuple every iteration could be very expensive, so instead let's do a topological sort.