[Tex/LaTex] A tree with complicated nodes as each child in tikz

tikz-pgftikz-trees

Trying to make a tree where each child is a set of nodes that can be created separately and then linked somehow in to different positions in a tree.

Lets say I have a group of nodes and edges such as

\node (1) at (0,1) {1};
\node (2) at (0,2) {2};
\draw(->, bend left=90, dotted) (1.north) -- (2.north);

I have looked at trees and it seems that each child can only be one node. I would like to be able to use, for example, the three above commands and treat them as one child (and have the relative coordinates kept within a child). Perhaps it is possible to do this with a macro(?) although I can't find any examples/literature on it.

For example, something like the following:

\documentclass{article}
\usepackage{tikz}
\begin{document}

\begin{tikzpicture} 
  \node {root} 
    child {\node (1) at (0,0) {A}; \node (1) at (0,0) {B}};
    child {\node (1) at (0,0) {C}; \node (1) at (0,0) {D} 
      child {\node (1) at (0,0) {C};} 
      child {\node (1) at (0,0) {D};} 
    }; 
\end{tikzpicture}

\end{document}

Best Answer

It is not entirely clear to me what you after, but you can certainly write subtrees as macros, which should start with a child. Alternatively you can use pics. I give three examples:

Sample output level

\documentclass{article}

\usepackage{tikz}

\begin{document}

\newcommand{\mysubtree}[2]{child {node {#1}} 
      child {node {#2}}}

\begin{tikzpicture}[level 2/.style={sibling distance=1cm}] 
  \node (R) {root} 
  child {node  {A}
  child {node  {B}}}
  child {node {C} \mysubtree DE}
  child {node {F} \mysubtree GH}; 
\end{tikzpicture}

\end{document}

You can add quite complicated code to these macros:

Sample coloured output

\documentclass{article}

\usepackage{tikz}

\begin{document}

\newcommand{\mysubtree}[3]{child {node[red] {#1}
      child {node[draw] {#2}} 
      child[edge from parent path={(\tikzparentnode\tikzparentanchor)
        edge [bend left] (\tikzchildnode\tikzchildanchor)}]
        {node[circle,fill=green] {#3} }}} 


\begin{tikzpicture} 
  \node {root} 
  child {node  {A}
   child {node  {B}
    \mysubtree CDE
    \mysubtree FGH}}; 
\end{tikzpicture}

\end{document}

Finally using pics may be closest to what you ask. You can simply place a pic instead of a node but there is an anchoring problem for the edges, see the right most node below. Instead place these together with a dummy node that takes is a blank rectangle of appropriate size:

Sample pic output

\documentclass{article}

\usepackage{tikz}
\tikzset{ mynode/.pic={
  \node (1) at (-0.25,0) {1};
  \node (2) at (0.25,0) {2};
  \draw[->, bend left=90, dotted] (1.north) -- (2.north);
  },
  mypic/.style={rectangle,minimum size=4ex}
}

\begin{document}

\begin{tikzpicture}
  \node (R) {root} 
  child {node  {A}
  child {node  {B}}}
  child { node[mypic] {} pic {mynode} }
  child { node[mypic] {} pic {mynode} }
  child { pic {mynode} }; 
\end{tikzpicture}

\end{document}