The restricted energy of nodes is one of the most important challenges in wireless sensor networks. Since data transmissions among nodes consume most of the nodes' energy, thus, minimizing the unnecessary transmissions reduces the consumed energy. One of the sources of this problem is the redundancy of raw data that can be eliminated at the aggregation points. As a result, data aggregation can be considered as an effective strategy to tackle the mentioned issue and to optimize the communication energy consumption. In this paper, the sensor nodes are organized in a tree structure, and the data aggregation are done in intermediate nodes at the junction of tree branches. One of the main characteristics of tree protocols is reduction of energy consumption through optimizing the structure of a data aggregation tree. For this, this paper proposes to apply a swarm intelligent algorithm named river formation dynamics. The simulation results show that the proposed algorithm outperforms in comparison to the famous ant colony optimization algorithm in terms of network lifetime. Simulations show that the proposed algorithm makes nearly 4% and 50% improvement in lifetime of wireless sensor networks than ant colony optimization and shortest path routing, respectively.