This is known as the VSEPR theory (Valence Shell Electron Pair Repulsion theory). Basically, valence shell electrons are meant to repel each other. Hence, in linear molecules, the atoms are placed as far away as possible. The reason for the difference in geometry of different molecules is due to the fact that they consist of different numbers of atoms on the central atom. With tetrahedral molecules, there are four atoms bound to the central atom. As a result, there is less "flexibility" to place the atoms as far away as possible (~109 degrees), in contrast to linear molecules when they are 180 degrees apart.
Also, lone pairs repel more than bond pairs. This is the reason why some molecules are bent and why others are linear.