我是 tikz 的新手,想用包 forest 绘制重组/合并二叉树。我最初使用了Tikz-tree 合并/重组节点,但由于我也使用非合并树和 forrest,我更喜欢单一解决方案。因此,是否可以合并下面标记为 5 的两个节点?
\documentclass{article}
\usepackage{tikz}
\usepackage{amsmath}
\usetikzlibrary{automata}
\usetikzlibrary{calc,arrows.meta,positioning}
\newcommand{\iddots}{\reflectbox{$\ddots$}}
\usepackage{forest}
\usetikzlibrary{arrows.meta}
\begin{document}
\begin{forest}
for tree={
semithick,
minimum size=1.3em, inner sep=0pt,
math content,
% tree
l sep =12mm,
s sep = 6mm,
/tikz/arr/.style = { -{Triangle[angle=45:2pt 3]}, shorten >=1pt},
/tikz/ELS/.style = {% Edge Label Style
pos=0.5, node
font=\footnotesize, text=blue, anchor=#1},
EL/.style={if n=1{edge label={node[ELS=east]{$#1$}}}
{edge label={node[ELS=west]{$#1$}}}}
%%%% diagram body
[1, label=$\tilde{S}^1$, tier=0
[2, EL=1-p
[4, EL=1-p]
[5, EL=p]
]
[3, EL=p
[5, EL=1-p]
[6, EL=p]
]
]
\end{forest}
\end{document}
答案1
像这样?
使用fixed edge angles
选项,用负数s sep
等于节点宽度的技巧。
编辑: 改进了边缘标签样式:
\documentclass[border=3.141592]{standalone}
%\documentclass{article}
\usepackage{forest}
\usetikzlibrary{arrows.meta}
\begin{document}
\begin{forest}
for tree={
% nodes
circle, draw, semithick,
minimum size=1.2em, inner sep=0pt, outer sep=0pt, %<---
math content,
% tree with fixed angles of edges
l sep = 11mm, % <---
calign = fixed edge angles, % <---
calign angle = 30, % <---
s sep=-1.2em, % <---
for current and siblings = {anchor=center},
/tikz/arr/.style = {draw=cyan!60, -{Triangle[angle=45:2pt 3]},
shorten <=\pgflinewidth, shorten >=1pt},
edge = arr,
%% edge labels
/tikz/ELS/.style = {% Edge Label Style
pos=0.5, node font=\scriptsize, inner sep=0pt,
text height=2ex, text depth=0.5ex, text=cyan, anchor=south #1},
EL/.style={if n=1{edge label={node[ELS=east]{$#1$}}}
{edge label={node[ELS=west]{$#1$}}}}
}% end of "for tree"
%%%% diagram body
[1, label=$\tilde{S}^1$
[2, EL=1-p
[4, EL=q]
[5,EL=1-q]
]
[3, EL=p
[, EL=q]
[6, EL=1-q]
]
]
\end{forest}
\end{document}
附录: 或者以下形式:
\documentclass[border=3.141592]{standalone}
%\documentclass{article}
\usepackage{forest}
\usetikzlibrary{arrows.meta}
\begin{document}
\begin{forest}
for tree={
% nodes
circle, draw, semithick,
minimum size=1.2em, inner sep=0pt,
anchor=north, % <--- new
math content,
% tree
l sep =12mm,
s sep = 3mm,
/tikz/arr/.style = {draw=cyan!60, shorten >=1pt,
-{Triangle[angle=45:2pt 3]}},
edge = arr,
%% edge labels
/tikz/ELS/.style = {% Edge Label Style
pos=0.5, node font=\tiny, inner sep=0pt, % <--- changed
text height=2ex, text depth=0.5ex, text=cyan, anchor=south #1},
EL/.style={if n=1{edge label={node[ELS=east]{$#1$}}}
{edge label={node[ELS=west]{$#1$}}}}
}% end of "for tree"
%%%% diagram body
[1, label=$\tilde{S}^1$
[2, EL=1-p, calign = last, name=n2 % <--- added calign
[4, EL=q]
[,phantom] % <--- changed
]
[,phantom[5, name=n5]] % <--- new
[3, EL=p, calign = first, name=n3 % <--- added calign
[,phantom] % <--- changed
[6, EL=1-q]
]
]
\draw[arr] (n2) -- (n5) node[ELS=west] {$1-q$};
\draw[arr] (n3) -- (n5) node[ELS=east] {$q$};
\end{forest}
\end{document}