# Stern-Brocot tree where each node has two fathers

I would like to draw a "tree" like the one in the picture below.

I tried the forest package, but I was only able to draw the tree with the black edges with root 1/1.

\documentclass{article}
\usepackage{forest}

\begin{document}

\begin{forest}
[$\frac{1}{1}$
[$\frac{1}{2}$
[$\frac{1}{3}$
[$\frac{1}{4}$
[ $\frac{1}{5}$ ]
[$\frac{2}{7}$] ]
[$\frac{2}{5}$
[$\frac{3}{8}$ ]
[$\frac{3}{7}$ ] ] ]
[$\frac{2}{3}$
[$\frac{3}{5}$
[$\frac{4}{7}$ ]
[$\frac{5}{8}$ ] ]
[$\frac{3}{4}$
[$\frac{5}{7}$ ]
[$\frac{4}{5}$ ] ] ] ]
[$\frac{2}{1}$
[$\frac{3}{2}$
[$\frac{4}{3}$
[$\frac{5}{4}$]
[$\frac{7}{5}$ ] ]
[$\frac{5}{3}$
[$\frac{8}{5}$ ]
[$\frac{7}{4}$ ] ] ]
[$\frac{3}{1}$
[$\frac{5}{2}$
[$\frac{7}{3}$ ]
[$\frac{8}{3}$ ] ]
[$\frac{4}{1}$
[$\frac{7}{2}$ ]
[$\frac{5}{1}$ ] ] ] ] ] ]
\end{forest}
\end{document}


I would like to draw the gray edges too and the two "roots" 0/1 and 1/0.

New contributor
cescomassa is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

This is a brute force solution. It should be possible to fully automatize this, i.e. let forest do everything, but I really do not know what the rules for the Stern-Brocot diagram are.

\documentclass{article}
\usepackage{forest}

\begin{document}

\begin{forest}
for tree={alias/.wrap pgfmath arg={a-#1}{id},
%label/.wrap pgfmath arg={[gray,font=\tiny,inner sep=0pt]above:#1}{id}
}
[$\frac{1}{1}$
[$\frac{1}{2}$
[$\frac{1}{3}$
[$\frac{1}{4}$
[$\frac{1}{5}$]
[$\frac{2}{7}$] ]
[$\frac{2}{5}$
[$\frac{3}{8}$]
[$\frac{3}{7}$] ] ]
[$\frac{2}{3}$
[$\frac{3}{5}$
[$\frac{4}{7}$]
[$\frac{5}{8}$] ]
[$\frac{3}{4}$
[$\frac{5}{7}$]
[$\frac{4}{5}$] ] ] ]
[$\frac{2}{1}$
[$\frac{3}{2}$
[$\frac{4}{3}$
[$\frac{5}{4}$]
[$\frac{7}{5}$] ]
[$\frac{5}{3}$
[$\frac{8}{5}$]
[$\frac{7}{4}$] ] ]
[$\frac{3}{1}$
[$\frac{5}{2}$
[$\frac{7}{3}$]
[$\frac{8}{3}$] ]
[$\frac{4}{1}$
[$\frac{7}{2}$]
[$\frac{5}{1}$] ] ] ] ] ]
\path (current bounding box.north west) node[below right] (tl) {$\frac{0}{1}$}
(tl) foreach \x in {2,...,6} {edge (a-\x)}
(current bounding box.north east) node[below right] (tr) {$\frac{1}{1}$}
(tr) foreach \x in {2,18,26,30,32} {edge (a-\x)}
(a-2) foreach \x in {11,15,17,19,20,21} {edge (a-\x)}
(a-3) foreach \x in {8,10,12,13} {edge (a-\x)}
(a-4) foreach \x in {7,9} {edge (a-\x)}
(a-11) foreach \x in {14,16} {edge (a-\x)}
(a-18) foreach \x in {23,25,27,28} {edge (a-\x)}
(a-19) foreach \x in {22,24} {edge (a-\x)}
(a-26) foreach \x in {29,31} {edge (a-\x)};
\end{forest}
\end{document}


If you uncomment

%label/.wrap pgfmath arg={[gray,font=\tiny,inner sep=0pt]above:#1}{id}


you will see where all the magic numbers come from:

One could optimize this (obvious options include math content), but given that there is surely a logic behind this diagram, it appears a bit unmotivated to seek a partial improvement.