[Tex/LaTex] Drawing a Cayley tree

tikz-pgftikz-trees

I'm new to Tikz so sorry if this is trivial. I'd like to draw a Cayley tree in Tikz that looks something like [this image I found on Google.

The catch is that I want alternating layers to be alternate node shapes — circle and square nodes. Secondly, I would like the circular nodes to have degree 3 and the square nodes to have degree 5. Is there some way to generate this without having to place each node manually where I want?

Best Answer

Second proposition (using two nested loops as suggested by marsupilam)

(Note: My previous proposition did not use the correct definition of degrees. Thanks to cfr and marsupilam for having noticed.)

Here is a pdflatex solution. The first node (the center) is c-0-1. The first level nodes are c-1-1, c-1-2 and c-1-3... The fourth level nodes are c-4-1, c-4-2, ... and c-4-96.

\documentclass[tikz]{standalone}
\tikzset{
  common/.style={draw,name=#1,node contents={},inner sep=0,minimum size=3},
  disc/.style={circle,common=#1},
  square/.style={rectangle,common={#1}},
}
\begin{document}
\begin{tikzpicture}
  \draw (0,0) node[disc=c-0-1];
  \xdef\radius{0cm}
  \xdef\level{0}
  \xdef\nbnodes{1}
  \xdef\degree{(3+1)} % special degree just for the root node
  \foreach \ndegree/\form in {5/square,3/disc,5/square,3/disc}{
    \pgfmathsetmacro\nlevel{int(\level+1)}
    \pgfmathsetmacro\nnbnodes{int(\nbnodes*(\degree-1))}
    \pgfmathsetmacro\nradius{\radius+1cm}
    \draw[red] (c-0-1) circle(\nradius pt);
    \foreach \div in {1,...,\nnbnodes} {
      \pgfmathtruncatemacro\src{((\div+\degree-2)/(\degree-1))}
      \path (c-0-1) ++({\div*(360/\nnbnodes)-180/\nnbnodes}:\nradius pt) node[\form=c-\nlevel-\div];
      \draw (c-\level-\src) -- (c-\nlevel-\div);
    }
    \xdef\radius{\nradius}
    \xdef\level{\nlevel}
    \xdef\nbnodes{\nnbnodes}
    \xdef\degree{\ndegree}
  }
\end{tikzpicture}
\end{document}

enter image description here