Optimal gathering of oblivious robots in anonymous graphs and its application on trees and rings