【LaTeX应用】画个复杂的二叉树

前面一篇文章已经说过关于用LaTeX画树形结构的问题,那个二叉树相对比较简单,没有替他的元素混杂。这里再画一个复杂点的案例,添加一些可能在实际应用中需要的元素,比如有头节点,表示整个二叉树的开始位置等。

在每个节点是否可以划分为多个,这也是一个常见的需求,具体的实现效果如图所示。       

        

【LaTeX应用】画个复杂的二叉树_第1张图片

下面是实现过程的主要代码部分,每条代码的具体语法这里不一一解释了,通过规范的排版,基本上已经将每条代码的含义解释清楚了,请耐心点阅读。这些代码可以直接运行,实现如图所示效果,可以当做模板应用。

\begin{tikzpicture}[
		scale = 1.5, transform shape, thick,
		every node/.style = {draw, circle, minimum size = 10mm},
		grow = down,  % alignment of characters
		level 1/.style = {sibling distance=3cm},
		level 2/.style = {sibling distance=4cm}, 
		level 3/.style = {sibling distance=2cm}, 
		level distance = 1.25cm
		]
		\node[fill = gray!40, shape = rectangle, rounded corners,
		minimum width = 2cm, font = \sffamily] {Coin flipping} 
		child { node[shape = circle split, draw, line width = 1pt,
			minimum size = 10mm, inner sep = 0mm, font = \sffamily\large,
			rotate=30] (Start)
			{ \rotatebox{-30}{H} \nodepart{lower} \rotatebox{-30}{T}}
			child {   node [head] (A) {}
				child { node [head] (B) {}}
				child { node [tail] (C) {}}
			}
			child {   node [tail] (D) {}
				child { node [head] (E) {}}
				child { node [tail] (F) {}}
			}
		};
		
		% Filling the root (Start)
		\begin{scope}[on background layer, rotate=30]
		\fill[head] (Start.base) ([xshift = 0mm]Start.east) arc (0:180:5mm)
		-- cycle;
		\fill[tail] (Start.base) ([xshift = 0pt]Start.west) arc (180:360:5mm)
		-- cycle;
		\end{scope}
		
		% Labels
		\begin{scope}[nodes = {draw = none}]
		\path (Start) -- (A) node [near start, left]  {$0.5$};
		\path (A)     -- (B) node [near start, left]  {$0.5$};
		\path (A)     -- (C) node [near start, right] {$0.5$};
		\path (Start) -- (D) node [near start, right] {$0.5$};
		\path (D)     -- (E) node [near start, left]  {$0.5$};
		\path (D)     -- (F) node [near start, right] {$0.5$};
		\begin{scope}[nodes = {below = 11pt}]
		\node [name = X] at (B) {$0.25$};
		\node            at (C) {$0.25$};
		\node [name = Y] at (E) {$0.25$};
		\node            at (F) {$0.25$};
		\end{scope}
		\draw[densely dashed, rounded corners, thin]
		(X.south west) rectangle (Y.north east);
		\end{scope}
		\end{tikzpicture}

 在导言区添加几行代码

\usepackage{tikz}
\usetikzlibrary{chains,scopes,positioning,backgrounds,shapes,fit,shadows,calc,arrows.meta}
\RequirePackage{amsmath,mathrsfs,amsfonts,amssymb}
\tikzset{
	head/.style = {fill = orange!90!blue,
		label = center:\textsf{\Large H}},
	tail/.style = {fill = blue!70!yellow, text = black,
		label = center:\textsf{\Large T}}
}

 

你可能感兴趣的:(LaTeX,latex,二叉树,tikz)