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+1instead of3) - I cannot use
\bt@nand\bt@din 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.




strrepeat(strcatis fromforest) that is used to place the0/1and1/0fractions in dependence of the maximum level. Those nodes will be placed wrongly if the tree doesn’t grow upwards or downwards. – Qrrbrbirlbel Sep 30 '13 at 17:27\edef\fracTop{...}or\def\fracTop{...}is exactly the same, because\numexpris unexpandable. You probably want\edef\fracTop{\number\numexpr#1+#3\relax\space}or you'll be calling\numexprvery deeply nested (one level added for each recursion step, so in the example they are three). The final\spaceis for terminating the<number>when used later (spaces after numbers are ignored inside\numexpr, because they follow a constant). – egreg Sep 30 '13 at 17:35\edef\FracTop{\number…}in earlier version of my codes and changed the implementation for some reason which I cannot remember anymore. I have now changed both implementations in my answer. The\spacedoesn’t seem to matter, though? – Qrrbrbirlbel Sep 30 '13 at 17:49\space, in this particular case, could be omitted. But be careful with the places you intend to use a<number>. – egreg Sep 30 '13 at 19:18