使用此代码:
\begin{tikzpicture}[level distance=1.5cm,
level 1/.style={sibling distance=1.3cm},
level 2/.style={sibling distance=1cm}]
level 3/.style={sibling distance=0.8cm}]
\tikzstyle{every node}=[circle,draw]
\node (Root) [red] {e}
child {
node {a}
child {
node {b}
child {node {c}}
}
child { node {d} }
}
child {
node {h}
}
child {
node {f}
child { node {g} }
};
\end{tikzpicture}
我制作了这张图片:
我的问题是如何在此图像上生成边权重,例如,如果我想要从 e 到 a 或从 a 到 b 的边权重,我该如何为这棵树生成它?
我正在使用这个库:\usetikzlibrary{trees}
答案1
您可以使用edge from parent
,但这可能需要切换回来。
\documentclass[tikz,border=5pt]{standalone}
\usetikzlibrary{trees}
\begin{document}
\begin{tikzpicture}[level distance=1.5cm,
level 1/.style={sibling distance=1.3cm},
level 2/.style={sibling distance=1cm}]
level 3/.style={sibling distance=0.8cm}]
\tikzstyle{every node}=[circle,draw]
\node (Root) [red] {e}
child {
node {a}
child {
node {b}
edge from parent[blue]
child {node[black] {c}
edge from parent[black]}
}
child { node {d} }
edge from parent[double]
}
child {
node {h}
}
child {
node {f}
child { node {g} }
};
\end{tikzpicture}
\end{document}
答案2
像这样?
对于边的标签服务edge from parent node[<options>] {<label>}
。它应该在正确的位置(在它之前的节点之后,你喜欢有标签),参见下面的mwe:
\documentclass[tikz,margin=3mm]{standalone}
\usetikzlibrary{trees}
\begin{document}
\begin{tikzpicture}[
level distance = 1.5cm,
level 1/.style = {sibling distance=1.3cm},
level 2/.style = {sibling distance=1.0cm},
level 3/.style = {sibling distance=0.8cm},
every node/.style = {circle,draw},
lbl/.style = {rectangle, draw=none, #1,% position
font=\footnotesize}
]
%
\node (Root) [red] {e}
child {node {a}
child {node {b}
child {node {c}
edge from parent node[lbl=left] {$bc$}
}
edge from parent node[lbl=left] {$ab$}
}
child {node {d}
edge from parent node[lbl=right] {$ad$}
}
edge from parent node[lbl=left] {$ea$}
}
child { node {h}}
child { node {f}
child { node {g} }
};
\end{tikzpicture}
\end{document}
选择边所使用的标签来指示节点名称以及边的起点和终点。您可以在此找到关于此内容的解释21.6 来自父节点的边,《tikz 和 pgf 手册》第 323 页,版本 3.0.1a,