If it had more edges than this, it would have to contain a cycle. Fewer edges, and it would be disconnected. A spanning tree for any connected graph G can be found by doing DFS or BFS from any node v . Whenever a new edge is traversed, just add that edge to the set of edges already in the tree. The root of T will be v .
G is the sum of the edge weights or costs for the graph.
Each edge may be weighted to model some situation, such as the time of travel between the nodes, or the cost of shipping a parcel from one point to another, or the resistance of a length of wire in a circuit. This is one algorithm to build a min-cost spanning tree. Select a first edge of lowest cost. If you quit before the tree has N - 1 edges, then report no spanning tree. Select the next node having the smallest distance.