# How to add children to previously-declared nodes using TikZ?

Here is a simple TikZ tree:

\begin{tikzpicture}
\node {root}
child {node {left}}
child {node {right}
child {node {child}}
child {node {child}}
};
\end{tikzpicture}


In this example, the children are appended to the root node in the same statement. How to attach children (child) to the root node in a later statement?

\begin{tikzpicture}
\node (root) {root}; % declare root

% do something else

... % reference root node and attach children to it
child {node {left}}
child {node {right}
child {node {child}}
child {node {child}}
};
\end{tikzpicture}


I want to do this because the root node is created in a loop.

• You need to be more specific. Maybe you could post exactly what you have in mind. First, you may want to name the first node in the tree (especially if you create more than one -- you specified that root node is created in a loop). Jan 13, 2021 at 17:01
• I attempted to clarify the question. Please let me know if it is still unclear. Jan 13, 2021 at 17:23
• I added a proposal, based on what I understood. Hope this'll work. Jan 13, 2021 at 17:37

OK, I understood, at least I think I did. Here's a proposal:

\documentclass[border=10pt]{standalone}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}

% Create first node which is the fake tree root node
\node (root) {root};

% Do whatever you want

% Call back your fake root node and place your real tree node on it
% using \phantom to exactly copy the fake one

\node at (root) {\phantom{root}}
child   {   node {left}}
child   {   node {right}
child {node {child 1}}
child {node {child 2}}
};
\end{tikzpicture}

\end{document}


Same image is produced, so I didn't add any.
All this, provided you do everything into the same tikzpicture.

I am not sure what exactly you want to achieve, but you can always name nodes to later reference them, like so:

\documentclass[tikz]{standalone}

\begin{document}
\begin{tikzpicture}

\node (root) {root}
child {node {left}}
child {node {right}
child {node {child}}
child {node (one) {child}}
};

\draw[red] (one) to [bend right=60] (root);

\end{tikzpicture}
\end{document}


• I realize my question was not crystal clear. I updated it. Jan 13, 2021 at 17:24
• Ok, this is indeed a bit different that what I understood. However, naming nodes should still be key here, I guess. Jan 13, 2021 at 17:43