1

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.

3
  • 1
    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).
    – SebGlav
    Jan 13, 2021 at 17:01
  • I attempted to clarify the question. Please let me know if it is still unclear.
    – DurandA
    Jan 13, 2021 at 17:23
  • I added a proposal, based on what I understood. Hope this'll work.
    – SebGlav
    Jan 13, 2021 at 17:37

2 Answers 2

2

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.

1

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}

enter image description here

2
  • I realize my question was not crystal clear. I updated it.
    – DurandA
    Jan 13, 2021 at 17:24
  • 1
    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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.