That's because you are only using the x-coordinates that the algorithm outputs for the visualization and completely ignore the y-coordinates by overwriting them with hard-coded "level" values.
This means that the algorithm indeed (most of the time) produces non-overlapping results, but your code introduces the overlaps by simply modifying the y-coordinates in a way that the nodes overlap.
If you replace the yOut(d)
part with a simple d.y
you will see the actual (internal) results and that the nodes won't overlap. But you don't get the levels visualized.
This strategy for producing a hierarchic layout (a.k.a Sugiyama layout) is not very clever and will produce bad results all of the time, unless you are very, very lucky.
Instead you should be looking for an implementation of a hierarchic layout that can properly deal with this case. If you need to stick with d3 you can try the (hardly maintained AFAIK) dagre layout. If you want to have more features and get better results, have a look at the hierarchic layout in yFiles for HTML.
Disclosure: I work for the company that creates the latter (commercial) product, but I do not represent my employer here on SO. I am absolutely convinced that the latter implementation is the best available implementation of the layout algorithm available for JavaScript.