如何在树中添加额外的边?

如何在树中添加额外的边?

我想画一棵带有一些边的树。请参阅下面给出的代码。

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}[level distance=1.5cm,
 level 1/.style={sibling distance=3cm},
 level 2/.style={sibling distance=1.5cm}]
\node {$1$}
  child {node {$2$}
  child {node {$4$}}
  child {node {$5$}}
}
child {node {$3$}
child {node {$6$}}
  child {node {$7$}}
};

 \end{tikzpicture}

  \end{document}

问题 :我想把节点做成小圆圈,如何在节点 4 和节点 5 之间插入边?

答案1

像这样:

在此处输入图片描述

\documentclass{article}
\usepackage{tikz}

\begin{document}
    \begin{tikzpicture}[
 level distance=1.5cm,
 level 1/.style={sibling distance=3cm},
 level 2/.style={sibling distance=1.5cm},
 every node/.style = {circle, draw, minimum size=1.2em,  inner sep=2pt}
                    ]
\node {$1$}
  child {node {$2$}
  child {node (n4) {$4$}}
  child {node (n5) {$5$}}
}
child {node {$3$}
child {node (n6) {$6$}}
  child {node {$7$}}
};
\draw (n4) -- (n5);
    \end{tikzpicture}
\end{document}

附录: 有了包forest代码就更简单了:

\documentclass{article}
\usepackage{forest}

\begin{document}
    \begin{forest}
for tree = {
    circle, draw, minimum size=1.2em,  inner sep=2pt,
    l sep = 12mm,
    s sep = 12mm,
    math content
            }
[1
    [2
        [4, name=n4]
        [5, name=n5]
    ]
    [3
        [6, name=n6]
        [7]
    ]
]
\draw (n4) -- (n5);
    \end{forest}
\end{document}

在此处输入图片描述

附录(2): 连接节点 4 和 6 并避开节点 5:

在此处输入图片描述

为此,您需要为节点“6”添加广告名称并绘制如下线条:

\draw (n4) to [bend right] (n6);

相关内容