[Tex/LaTex] How to draw the recursive H-Layout tree using Tikz

recursiontikz-pgftikz-trees

The following image shows a recursive H-Layout tree.

H-Layout

It is called H-Layout because of its H unit consisting of 7 nodes.

My problem is:

How to draw such tree in a recursive manner instead of drawing each node explicitly?

Best Answer

Code A (preferred)

\documentclass[tikz]{standalone}
\tikzset{if/.code n args={3}{\pgfmathparse{#1}%
  \ifnum\pgfmathresult=1\pgfkeysalso{#2}\else\pgfkeysalso{#3}\fi}}
\begin{document}
\begin{tikzpicture}[nodes=draw, thick,
  H/.style n args={3}{% #1 = direction, #2=initial length, #3=levels
    if={0<=#3}{
      append after command={\pgfextra{\let\tikzLastnode\tikzlastnode}
        node[HH={#1}{#2}{#3}, shift=(#1+180:#2)] at (\tikzLastnode) {} edge (\tikzLastnode)
        node[HH={#1}{#2}{#3}, shift=(#1:#2)]     at (\tikzLastnode) {} edge (\tikzLastnode)}
    }{}},
  HH/.style n args={3}{
    append after command={\pgfextra{\let\tikzLastnode\tikzlastnode}
      node[H={#1}{#2/2}{#3-1}, shift=(#1+90:#2)] at (\tikzLastnode) {} edge (\tikzLastnode)
      node[H={#1}{#2/2}{#3-1}, shift=(#1-90:#2)] at (\tikzLastnode) {} edge (\tikzLastnode)
    }}]
\node[H={0}{3cm}{3}] {};
\end{tikzpicture}
\end{document}

Code B

\documentclass[tikz]{standalone}
\tikzset{if/.code n args={3}{\pgfmathparse{#1}%
  \ifnum\pgfmathresult=1\pgfkeysalso{#2}\else\pgfkeysalso{#3}\fi}}
\begin{document}
\begin{tikzpicture}[nodes=draw, thick, every pin edge/.style={}, every pin/.style={draw},
H/.style n args={3}{% #1 = direction, #2=initial length, #3=levels
  if={0<=#3}{% .6666em are 2*inner sep, \pgflinewidths are outer seps. Hard-coded values!
    pin={[pin distance=#2,
      pin={[pin distance=#2, H={#1}{(#2-.6666em-\pgflinewidth)/2}{#3-1}]#1+90:},
      pin={[pin distance=#2, H={#1}{(#2-.6666em-\pgflinewidth)/2}{#3-1}]#1-90:}]#1:},
    pin={[pin distance=#2,
      pin={[pin distance=#2, H={#1}{(#2-.6666em-\pgflinewidth)/2}{#3-1}]#1+90:},
      pin={[pin distance=#2, H={#1}{(#2-.6666em-\pgflinewidth)/2}{#3-1}]#1-90:}]#1+180:},
  }{}}]
\node[H={0}{3cm-.6666em-\pgflinewidth}{3}] {};
\end{tikzpicture}
\end{document}

Output

enter image description here

Related Question