在用 TikZ 制作的树中,我想标记树的边缘。我在 StackExchange 上看到了使用的示例edge from parent node{label}
,但这似乎只适用于树的最后一条边缘,一直延伸到叶子。下面是我所指的一个例子(图片下方的代码)。
首先,我在 TikZ 中创建树并用 标记边edge from parent node{...}
,这对于连接到叶子的边很有效:
B
但是,如果我尝试做同样的事情来标记和之间的边缘BB
,则会发生以下情况:
以下是代码:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{trees}
\begin{document}
\begin{tikzpicture}[level distance=1.5cm,
level 1/.style={sibling distance=6cm},
level 2/.style={sibling distance=3cm},
level 3/.style={sibling distance=1.5cm},
edge from parent/.style={draw}]
\node{$\bullet$}
child {node {\texttt{B}}
child {node{\texttt{BB}}
child {node{\texttt{BBB}} edge from parent node[left]{$\frac{3}{4}$}}
child {node{\texttt{BBG}}}
}
child {node{\texttt{BG}}
child {node{\texttt{BGB}}}
child {node{\texttt{BGG}}}
}
}
child {node {\texttt{G}}
child {node{\texttt{GB}}
child {node{\texttt{GBB}}}
child {node{\texttt{GBG}}}
}
child {node{\texttt{GG}}
child {node{\texttt{GGB}}}
child {node{\texttt{GGG}}}
}
};
\end{tikzpicture}
\begin{tikzpicture}[level distance=1.5cm,
level 1/.style={sibling distance=6cm},
level 2/.style={sibling distance=3cm},
level 3/.style={sibling distance=1.5cm},
edge from parent/.style={draw}]
\node{$\bullet$}
child {node {\texttt{B}}
child {node{\texttt{BB}} edge from parent node[left]{$\frac{2}{3}$}
child {node{\texttt{BBB}} edge from parent node[left]{$\frac{3}{4}$}}
child {node{\texttt{BBG}}}
}
child {node{\texttt{BG}}
child {node{\texttt{BGB}}}
child {node{\texttt{BGG}}}
}
}
child {node {\texttt{G}}
child {node{\texttt{GB}}
child {node{\texttt{GBB}}}
child {node{\texttt{GBG}}}
}
child {node{\texttt{GG}}
child {node{\texttt{GGB}}}
child {node{\texttt{GGG}}}
}
};
\end{tikzpicture}
\end{document}
答案1
必须edge from parent node
在所有子节点后添加:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{trees}
\begin{document}
\begin{tikzpicture}[level distance=1.5cm,
level 1/.style={sibling distance=6cm},
level 2/.style={sibling distance=3cm},
level 3/.style={sibling distance=1.5cm},
edge from parent/.style={draw}]
\node{$\bullet$}
child {node {\texttt{B}}
child {node{\texttt{BB}}
child {node{\texttt{BBB}}
edge from parent node[left]{$\frac{3}{4}$}
}
child {node{\texttt{BBG}}}
edge from parent node[left,xshift=-4pt]{$\frac{2}{3}$}%<- moved
}
child {node{\texttt{BG}}
child {node{\texttt{BGB}}}
child {node{\texttt{BGG}}}
}
}
child {node {\texttt{G}}
child {node{\texttt{GB}}
child {node{\texttt{GBB}}}
child {node{\texttt{GBG}}}
}
child {node{\texttt{GG}}
child {node{\texttt{GGB}}}
child {node{\texttt{GGG}}}
}
};
\end{tikzpicture}
\end{document}