The structure of graphs with small M-indices