答案1
虽然从技术上讲这是一棵树,但它在视觉上像矩阵一样组织,这就是为什么我建议TikZ-CD对于它使用TikZ 矩阵内部。
TikZ 矩阵的工作方式类似于tabular
或array
环境,其中每个单元格由 分隔&
,每行由 分隔\\
。
但是,TikZ-CD 添加了\arrow
(或更短:)\ar
宏,指定在单元格之间画一条线。
通常,人们会写类似的东西来指定指向右的\ar[r]
箭头r
,类似地,l
和u
存在d
(左,上,下)。TikZ-CD 还为这些提供了“快捷方式”:\rar
,,,,。\lar
\uar
\dar
对于小注释,我定义了键from above
、from below
和from left
,from right
它们放置一个箭头,从该方向指向该单元格中的节点。箭头开头的文本可以在引号内给出。
代码
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{arrows.meta, cd, quotes}
\tikzcdset{
from direction/.style={
leftarrow, at end, to path={--++(#1:1em)\tikztonodes}},
/utils/temp/.style args={#1:#2:#3}{
from #1/.style={start anchor=#2, from direction=#3, #1}},
/utils/temp/.list={
below:south:down, above:north:up, left:west:left, right:east:right},
math mode with extras/.style 2 args={
math mode=false,
/tikz/matrix of nodes/.append style={
execute at begin node={$#1}, execute at end node={#2$}}}}
\begin{document}
\begin{tikzcd}[
math mode with extras = \{\},
arrow style=tikz, sep=1em,
labels={auto=false, font=\footnotesize},
arrows={dash, thick},
cells={nodes={
circle, draw=red, inner sep=+.2em,
text width={width("$\{b, c, e\}$")}, align=center}},
]
b, g \rar \ar[from above, "Root"]
& b \dar \\
& b, c \dar \\
b, c, e \dar
& b, c, e \lar \rar \ar[from below, "Join"]
& b, c, e \dar \\
b, e \dar
& & b, e \dar \ar[from left, "Introduce $b$"] \\
b \dar
& & e \dar \ar[from left, "Forget $(f)$"] \\
a, b \dar \ar[from right, "Node $i$"]
& & e, f \dar \\
d, a, b \dar
& & f \ar[from left, "Leaf"] \\
b, d \rar
& d
\end{tikzcd}
\end{document}
输出
答案2
使用该库的解决方案chains
:
\documentclass[border=10pt]{standalone}
\usepackage{mathpazo}
\usepackage{tikz}
\usetikzlibrary{chains, scopes}
\begin{document}
\begin{tikzpicture}[
thick,
node distance=5mm,
every join/.style={
shorten >=1pt,
shorten <=1pt,
},
every pin/.style={
font=\small,
pin edge={
thick,
black,
shorten <=2pt,
<-
}
},
every on chain/.style={
join,
every join/.style=->,
circle,
draw=red,
inner sep=3.5pt,
text width=3.5em,
align=center,
execute at begin node={\(\{},
execute at end node={\}\)}
}
]
{ [start chain=going right]
\node[on chain, pin={above:Root}] {b,g};
\node[on chain] {b};
\node[on chain, continue chain=going below] {b,c};
\node[on chain, pin={below:Join}] {b,c,e};
{ [start branch=A going left]
\node[on chain] {b,c,e};
\node[on chain, continue chain=going below] {b,e};
\node[on chain] {b};
\node[on chain, pin={right:Node $i$}] {a,b};
\node[on chain] {d,a,b};
\node[on chain] {b,d};
\node[on chain, continue chain=going right] {d};
}
{ [start branch=B going right]
\node[on chain] {b,c,e};
\node[on chain, continue chain=going below, pin={left:Introduce $(b)$}] {b,e};
\node[on chain, pin={left:Forget $(f)$}] {e};
\node[on chain] {e,f};
\node[on chain, pin={left:Leaf}] {f};
}
}
\end{tikzpicture}
\end{document}