12

I need to be able to connect any arbitrary nodes in a tree to each other. I am using the tree package in tikz to create my tree. I cannot figure out though how to connect to nodes by let say a draw or path command. here is a minimal example. Let say I like to connect node F to node D, any suggestions would be truly appreciated.

Artimess

\documentclass[10pt]{book}
\usepackage{tikz}
\usetikzlibrary{backgrounds}
\usetikzlibrary{trees,positioning,arrows}
\begin{document}
\begin{tikzpicture}[scale=0.8,font=\small, edge from parent fork down,
every node/.style={fill=blue!10},
edge from parent/.style={red,thick,draw},
level 1/.style={sibling distance=8cm},
level 2/.style={sibling distance=4.5cm}]
\node {A} 
 child {node {B}
   child {node {C} }  
  child {node {D}  child{node{E}}}} 
 child {node {F}
  child {node {G}}
  };
\end{tikzpicture}
\end{document}
Stefan Kottwitz
  • 231,401
artimess
  • 4,301

2 Answers2

13

I find that adding labels to the nodes makes this work. Note the (D) and (F) in the syntax for the corresponding nodes.

\documentclass[10pt]{book}
\usepackage{tikz}
\usetikzlibrary{backgrounds}
\usetikzlibrary{trees,positioning,arrows}
\begin{document}
\begin{tikzpicture}[scale=0.8,font=\small, edge from parent fork down,
every node/.style={fill=blue!10},
edge from parent/.style={red,thick,draw},
level 1/.style={sibling distance=8cm},
level 2/.style={sibling distance=4.5cm}]
\node {A} 
 child {node {B}
   child {node {C} }  
  child {node (D) {D}  child{node{E}}}} 
 child {node (F) {F}
  child {node {G}}
  };
\draw (F) -- (D);
\end{tikzpicture}
\end{document}

(Though I don't discount the possibility that trees have an implicit labelling system in the same fashion as matrices.)

Andrew Stacey
  • 153,724
  • 43
  • 389
  • 751
3

Of a (root) node, the child node number n in level 1 can be accessed by (root-n), in level 2 as child number n of the child number m as (root-m-n) etc centera. So here's the modified example with the implicit naming approach:

\documentclass[10pt]{book}
\usepackage{tikz}
\usetikzlibrary{backgrounds}
\usetikzlibrary{trees,positioning,arrows}
\begin{document}
\begin{tikzpicture}[scale=0.8,font=\small, edge from parent fork down,
  every node/.style={fill=blue!10},
  edge from parent/.style={red,thick,draw},
  level 1/.style={sibling distance=8cm},
  level 2/.style={sibling distance=4.5cm}]
  \node (root) {A} 
    child {node {B}
      child {node {C} }  
      child {node {D}
        child {node{E}}}} 
    child {node {F}
      child {node {G}}
    };
  \draw[->, dashed] (root-2) -- (root-1-2);
\end{tikzpicture}
\end{document}

tree

Stefan Kottwitz
  • 231,401