我有一棵树,结果是一个三叉树。代码如下
\begin{tikzpicture}
\tikzset{level distance=18pt,edge from parent/.style={draw, edge from parent path={(\tikzparentnode) -- (\tikzchildnode)}}}
\Tree [.$S$ [.$S$ [.$S$ ( [.$S$ [.$S$ $a$ ] $+$ [.$S$ $b$ ] ] ) ] $\times$ [.$S$ $b$ ] ] $+$ [.$S$ [.$S$ $b$ ] $\times$ [.$S$ $a$ ] ] ]
\end{tikzpicture}
输出:
我想以某种方式修改代码,以拉直树的 0 和 1 级的 S 的中间边。我阅读了文档,并搜索了可能的解决方案,但没有找到任何解决方案。
答案1
如果你愿意改变forest
,这里有一个选项:
\documentclass{article}
\usepackage{forest}
\begin{document}
\begin{forest}
for tree={
math content,
s sep+=5pt,
}[S
[S
[S
[(
]
[S
[S
[a]
]
[+
]
[S
[b]
]
]
[)
]
]
[\times
]
[S
[b]
]
]
[+,before computing xy={s=(s("!p")+s("!n"))/2}
]
[S
[S
[b]
]
[\times
]
[S
[a]
]
]
]
\end{forest}
\end{document}
如果您想坚持tikz-qtree
,这里有一个选择:
\documentclass{article}
\usepackage{tikz-qtree}
\begin{document}
\begin{tikzpicture}
\tikzset{
level 1/.style={sibling distance=20pt},
level 2/.style={sibling distance=30pt},
level distance=18pt,
edge from parent/.style={
draw,
edge from parent path={(\tikzparentnode) -- (\tikzchildnode)}
}
}
\Tree
[.\node[name=S0] {$S$};
[.\node[name=S1left] {a$S$};
[.\node[name=S2left] {b$S$}; ( [.$S$ [.$S$ $a$ ] \node {$+$}; [.$S$ $b$ ] ] ) ]
[.$S$ $b$ ]
]
[.$S$ [.$S$ $b$ ] $\times$ [.$S$ $a$ ] ]
]
\node (add1) at (S0|-S1left) {$+$};
\node (add2) at (S1left|-S2left) {$\times$};
\draw (S0) -- (add1);
\draw (S1left) -- (add2);
\end{tikzpicture}
\end{document}