I am trying to build a Stern-Brocot tree (enumeration of rationals).
The result is nearly acceptable, but I am still dissatisfied with the following points.
- The edge from the parents goes to the middle of the child node, not the upper border.
- The command does not (re)evaluate it's arguments at each iteration (we keep
1+1+1
instead of3
) - I cannot use
\bt@n
and\bt@d
in the recursive calls, as they are somehow messed up (why ?). - I have to give a name to my nodes, which is useless, but LaTeX won't compile without.
Here is the code :
\documentclass{standalone}
\usepackage{tikz}
\usepackage{etoolbox}
\newcommand{\eval}[1]{\pgfmathparse{int(#1)}\pgfmathresult}
\makeatletter % We can use the `@` symbol in macro names
\def\mybtree#1#2#3#4#5{%
\pgfextra{ % Allows us to use non-drawing commands
\pgfmathtruncatemacro\bt@depth{#5} % Current depth
\pgfmathtruncatemacro\bt@ndepth{\bt@depth - 1} % Next depth
\pgfmathtruncatemacro\bt@n{#1+#3}
\pgfmathtruncatemacro\bt@d{#2+#4}
%% Calculate the sibling distance
% distance = 2^{remaining depth}
\pgfmathsetmacro\bt@sdistance{pow( 2, \bt@depth)}
}
node (\bt@n/\bt@d) {$\frac{\eval{#1+#3}}{ \eval{#2+#4}}$}
\ifnumgreater{\bt@depth}{0}{% if( depth > 0 ) then:
child [sibling distance=\bt@sdistance*2em] {
\mybtree{#1}{#2}{#1+#3}{#2+#4}{\bt@ndepth}
}
child [sibling distance=\bt@sdistance*2em] {
\mybtree{#1+#3}{#2+#4}{#3}{#4}{\bt@ndepth}
}
}{% else:
%% Do nothing
}
}
\newcommand*{\btree}[1]{\mybtree{0}{1}{1}{0}{#1}}
\makeatother
\begin{document}
%% Now we can draw our tree
\begin{tikzpicture}
\draw \btree{3};
\end{tikzpicture}
\end{document}
It should give something like this
So any help is welcome.
Best Answer
Can I offer you a
forest
?Code
Output
Code (with more stuff)
Output (with more stuff)