A connected, undirected graph G that has no cycles is a tree! Any tree has exactly n - 1 edges, so we can simply traverse the edge list of the graph and count the edges. If we count n - 1 edges then we return “yes” but if we reach the nth edge then we return “no”. This takes O (n) time because we look at at most n edges.
But if the graph is not connected,then we would have to use DFS. We can traverse through the edges and if any unexplored edges lead to the visited vertex then it has cycle.