我一直在使用以下代码创建二叉树和平面树:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning,chains,fit,shapes,calc}
\begin{tikzpicture}
\node[circle,draw](z){}
child[missing]{}
child{
node[circle,draw]{} child{node[circle,draw] {}} child[missing] };
\end{tikzpicture}
\end{document}
答案1
由于inner sep
节点数,圆圈很大。您可以使用选项inner sep=<length>
(例如inner sep=1pt
)设置它,为每个节点单独设置,或者为整个图片设置
\begin{tikzpicture}[inner sep=1pt]
或者您可以为节点设置样式,以便轻松地单独更改其外观,如下所示
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning,chains,fit,shapes,calc}
\begin{document}
\begin{tikzpicture}
\tikzset{dot/.style={inner sep=1pt,circle,draw,fill},
circ/.style={inner sep=1pt,circle,draw}}
\node[dot](z){}
child[missing]{}
child{
node[dot]{} child{node[circ] {}} child[missing] };
\end{tikzpicture}
\end{document}
在示例中,新样式dot
和circ
仅在 tikzpicture 中可用。如果将这两行移到\tikzset
序言中,它们将适用于所有图片。
答案2
如果您需要绘制许多棵树,那么学习 Forest 是值得的,因为它允许您创建强大的样式,并可将其应用于极其简洁的树规范。
例如,定义三种样式,,dot tree
并dot tree spread
允许add arrow
我们编写
\begin{forest}
dot tree spread,
add arrow,
[[[][]][][[[][][]]][]]
\end{forest}
\begin{forest}
dot tree spread,
add arrow,
where level=0{!1.no edge, coordinate}{
if n=1{}{
edge path'={(!p) -- ()},
},
},
[[[][]][][[[][][]]][]]
\end{forest}
\begin{forest}
dot tree,
where n children=0{
before computing xy={l*=.5, s*=.5},
edge+={densely dashed},
}{},
[[[][[][]]][[][[[][]][[[][[][[][]]]][]]]]]
\end{forest}
生成问题中所示的一系列三棵树:
完整代码:
\documentclass[border=10pt]{standalone}
\usepackage{forest}
\usetikzlibrary{arrows.meta}
\begin{document}
\forestset{
dot tree/.style={
/tikz/>=Latex,
for tree={
inner sep=1pt,
fill,
draw,
circle,
calign angle=45,
calign=fixed edge angles,
},
baseline,
before computing xy={
where n children>=4{
tempcounta/.option=n children,
tempdima/.option=!1.s,
tempdimb/.option=!l.s,
tempdimb-/.register=tempdima,
tempdimc/.process={RRw2+P {tempcounta}{tempdimb}{##2/(##1-1)}},
for children={
if={>On>OR<&{n}{1}{n}{tempcounta}}{
s/.register=tempdima,
s+/.process={ORw2+P {n} {tempdimc} {(##1-1)*##2} }
}{},
},
}{},
},
},
dot tree spread/.style={
dot tree,
for tree={fit=rectangle},
},
add arrow/.style={
tikz+={
\draw [thick, blue!15!gray] (current bounding box.east) ++(2.5mm,0) edge [->] ++(10mm,0) ++(2.5mm,0) coordinate (o);
}
}
}
\begin{forest}
dot tree spread,
add arrow,
[[[][]][][[[][][]]][]]
\end{forest}
\begin{forest}
dot tree spread,
add arrow,
where level=0{!1.no edge, coordinate}{
if n=1{}{
edge path'={(!p) -- ()},
},
},
[[[][]][][[[][][]]][]]
\end{forest}
\begin{forest}
dot tree,
where n children=0{
before computing xy={l*=.5, s*=.5},
edge+={densely dashed},
}{},
[[[][[][]]][[][[[][]][[[][[][[][]]]][]]]]]
\end{forest}
\end{document}