In this paper, we design and implement a scheme to build an optimal spanning tree over a hybrid network composed of SDN and legacy switches. SDN is an emerging network technology and gradually gaining adoption worldwide. However, during the technology transition period, which may last several years from now on, inevitably SDN switches and legacy switches will need to coexist in a network. In a legacy network with loops, the IEEE 802.11D distributed spanning tree protocol is used to construct a spanning tree to avoid the packet broadcast storm problem. In an SDN network, the SDN controller can use the collected global knowledge of the network topology to centrally construct a spanning tree to solve this problem. However, so far there is no scheme to integrate together the spanning trees separately built in multiple isolated legacy networks and isolated SDN networks to build an optimal spanning tree across the hybrid network. Our scheme presented in this paper is the first scheme designed and implemented for this purpose. In this paper, we used the EstiNet OpenFlow network simulator and emulator to simulate hybrid networks. Our scheme is implemented as a module of the Floodlight SDN controller to construct an optimal spanning tree over the simulated hybrid networks. Our simulation results show that our scheme can correctly generate an optimal spanning tree based on two performance metrics: The average path latency and the average path throughput of a spanning tree.