C*-algebras associated to monoids and groupoids, and Bass-Serre theory for groupoids