See spanning-tree algorithm.