\documentclass{article}
\usepackage{tikz}
\begin{document}
\usetikzlibrary{positioning,trees}
\begin{tikzpicture}[level/.style={sibling distance=85mm/#1}]
\node {T(n)}
child {node {$T\left(\left(\frac{1}{3}\right)^{1}\cdot\left(\frac{2}{3}\right)^{0}\cdot n\right)$}
child {node {$T\left(\left(\frac{1}{3}\right)^{2}\cdot\left(\frac{2}{3}\right)^{0}\cdot n\right)$}
child {node {$T\left(\left(\frac{1}{3}\right)^{2}\cdot\left(\frac{2}{3}\right)^{0}\cdot n\right)$}}
child {node {$T\left(\left(\frac{1}{3}\right)^{1}\cdot\left(\frac{2}{3}\right)^{1}\cdot n\right)$}}}
child {node {$T\left(\left(\frac{1}{3}\right)^{1}\cdot\left(\frac{2}{3}\right)^{1}\cdot n\right)$}}
}
child {node {$T\left(\left(\frac{1}{3}\right)^{0}\cdot\left(\frac{2}{3}\right)^{1}\cdot n\right)$}
child {node {$T\left(\left(\frac{1}{3}\right)^{2}\cdot\left(\frac{2}{3}\right)^{0}\cdot n\right)$}}
child {node {$T\left(\left(\frac{1}{3}\right)^{1}\cdot\left(\frac{2}{3}\right)^{1}\cdot n\right)$}}
};
\end{tikzpicture}
\end{document}
我正在尝试使用 tree 绘制简单的递归树,但节点超出了页面边界。我已经尝试过 \begin{center}/\centering
答案1
您可以设置scale
和transform shape
选项来调整整个tikzpicture
环境内容的大小:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning,trees}
\begin{document}
\begin{tikzpicture}[level/.style={sibling distance=85mm/#1}, scale=0.6, transform shape]
\node {T(n)}
child {node {$T\left(\left(\frac{1}{3}\right)^{1}\cdot\left(\frac{2}{3}\right)^{0}\cdot n\right)$}
child {node {$T\left(\left(\frac{1}{3}\right)^{2}\cdot\left(\frac{2}{3}\right)^{0}\cdot n\right)$}
child {node {$T\left(\left(\frac{1}{3}\right)^{2}\cdot\left(\frac{2}{3}\right)^{0}\cdot n\right)$}}
child {node {$T\left(\left(\frac{1}{3}\right)^{1}\cdot\left(\frac{2}{3}\right)^{1}\cdot n\right)$}}}
child {node {$T\left(\left(\frac{1}{3}\right)^{1}\cdot\left(\frac{2}{3}\right)^{1}\cdot n\right)$}}
}
child {node {$T\left(\left(\frac{1}{3}\right)^{0}\cdot\left(\frac{2}{3}\right)^{1}\cdot n\right)$}
child {node {$T\left(\left(\frac{1}{3}\right)^{2}\cdot\left(\frac{2}{3}\right)^{0}\cdot n\right)$}}
child {node {$T\left(\left(\frac{1}{3}\right)^{1}\cdot\left(\frac{2}{3}\right)^{1}\cdot n\right)$}}
};
\end{tikzpicture}
\end{document}
答案2
我会使用forest
。不仅因为它更节省空间,还因为您可以以编程方式创建树。(全部功劳归功于 Sašo Zivanović 和 cfr 为我们提供包和许多此类示例。)
\documentclass{article}
\usepackage{geometry}
\usepackage[edges]{forest}
\begin{document}
\begin{forest}
for tree={edge={semithick,draw},
l sep+=1ex,s sep+=-1ex,
if level=0{}{delay={%
content/.wrap 2 pgfmath
args={$\pgfmathtruncatemacro{\myn}{min(2,#1)+1-#2}
\pgfmathtruncatemacro{\mym}{#2-1}
T\left(\left(\frac{1}{3}\right)^{\myn}\left(\frac{2}{3}\right)^{\mym}n\right)$}{level}{n}}}}
[$T(n)$
[
[
[]
[]
]
[
]
]
[
[
]
[
]
]
]
\end{forest}
\end{document}
如您所见,您不必输入公式。如果您有另一个递归,您只需更改公式即可。