我試圖用一種舊的方式來表示 AVL,這是我所學的,並且發現與當今最常見的書籍相比,它更直觀地顯示。具有我感興趣的功能的原始圖像如下所示尼克勞斯沃斯 1986 年書和一些手寫筆記。
雖然視覺化可能是特定的,但表示 AVL 是計算機科學的通用資料結構概念,其目的實際上是使用此類繪圖作為講義。所以我相信它對更廣泛的受眾有用。
從這本書(書)中,我試圖準確地了解它所顯示的內容:Some nodes as circles
,some as long vertical rectangles
,用虛線突出顯示樹的底部部分,以及一個帶有 X 表示刪除節點的單一節點。有些矩形位於上方、內部和下方,如圖所示。我一直在嘗試將虛線表示為某種 tikz 節點並相應地定位,但沒有運氣。
從手寫筆記中,我試圖獲取numbers around the nodes (-2, -1, h-1, etc)
矩形上的字母“A、B、C、D”,以及circle oriented arrows to indicate rotation direction
.
答案1
基於 TikZ 的forest
包裹似乎相對有效地完成這項工作。下面的範例應該可以幫助您入門。
我定義了兩種節點樣式,
circnode
將節點格式化為圓形rectnode=<num>
將節點格式化為矩形,高度等於<num>
x.5cm
此外,我定義了一個宏\crossnode
,用於將交叉框附加到指定位置(在您的範例中,這通常是(some rectnode.south)
)
最後,手動繪製兩條虛線並將其放在背景圖層上。
前兩種情況的代碼
\documentclass{article}
\usepackage{forest}
\usetikzlibrary{backgrounds}
\forestset{
circnode/.style={circle,draw,minimum size=.5cm,inner sep=0},
rectnode/.style={draw,minimum width=.5cm,fill=white,minimum height=#1*.5cm,child anchor=north,anchor=north},
}
\newcommand\crossnode[2][anchor=north]{
\node(temp)[draw,fill=white,minimum size=.5cm,yshift=\pgflinewidth,#1]at(#2){};
\draw(temp.north west)--(temp.south east) (temp.north east)--(temp.south west);
}
\begin{document}
\begin{forest}
for tree={l+=.5cm,s sep=1cm},
[
[B,circnode
[A,circnode
[,rectnode=3,name=n][,rectnode=3]
]
[,rectnode=3]
]
]
\crossnode[anchor=north]{n.south}
\begin{scope}[on background layer]
\draw[dashed,thin] let \p1=(temp.north), \p2=(current bounding box.west), \p3=(current bounding box.east) in
(\x2-.5cm,\y1)--(\x3+.5cm,\y1) (\x2-.5cm,\y1+.5cm)--(\x3+.5cm,\y1+.5cm);
\end{scope}
\end{forest}
\begin{forest}
for tree={l+=.5cm,s sep=1cm},
[
[C,circnode
[A,circnode,
[,rectnode=3]
[B,circnode
[,rectnode=2,name=n1]
[,rectnode=2,name=n2]
]
]
[,rectnode=3]
]
]
\crossnode{n1.south}
\crossnode{n2.south}
\begin{scope}[on background layer]
\draw[dashed,thin] let \p1=(temp.north), \p2=(current bounding box.west), \p3=(current bounding box.east) in
(\x2-.5cm,\y1)--(\x3+.5cm,\y1) (\x2-.5cm,\y1+.5cm)--(\x3+.5cm,\y1+.5cm);
\end{scope}
\end{forest}
\end{document}