在树中的节点周围放置一个三角形

在树中的节点周围放置一个三角形

我有一棵充满数字的树,我想通过在其周围画一个三角形来标记子树。我似乎无法让它工作。

我的尝试:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes,fit}
\begin{document}
\begin{tikzpicture}
\node at (0,0) {3};

\node (7) at (-1/2,-1) {7};
\node at (1/2,-1) {4};

\node at (-1,-2) {2};
\node at (0,-2) {4};
\node at (1,-2) {6};

\node (8) at (-3/2,-3) {8};
\node at (-1/2,-3) {5};
\node (9) at (1/2,-3) {9};
\node at (3/2,-3) {3};

\node[isosceles triangle,fit = (7) (8) (9)] {};
\end{tikzpicture}
\end{document}

答案1

您需要明确添加draw选项(红色三角形)才能使用fit库,或者您可以使用calcpgf库来计算三角形的顶点(蓝色三角形):

在此处输入图片描述 在此处输入图片描述


代码:draw选项:

\documentclass[border=5pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes,fit}
\begin{document}
\begin{tikzpicture}
\node at (0,0) {3};

\node (7) at (-1/2,-1) {7};
\node at (1/2,-1) {4};

\node at (-1,-2) {2};
\node at (0,-2) {4};
\node at (1,-2) {6};

\node (8) at (-3/2,-3) {8};
\node at (-1/2,-3) {5};
\node (9) at (1/2,-3) {9};
\node at (3/2,-3) {3};

\node[isosceles triangle,fit = (7) (8) (9),draw=red,thick] {};
\end{tikzpicture}
\end{document}

代码:计算顶点:

\documentclass[border=5pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes,fit, calc}

\pgfmathsetmacro{\sinOffset}{sin(60)}
\pgfmathsetmacro{\cosOffset}{cos(60)}

\begin{document}
\begin{tikzpicture}
\node at (0,0) {3};

\node (7) at (-1/2,-1) {7};
\node at (1/2,-1) {4};

\node at (-1,-2) {2};
\node at (0,-2) {4};
\node at (1,-2) {6};

\node (8) at (-3/2,-3) {8};
\node at (-1/2,-3) {5};
\node (9) at (1/2,-3) {9};
\node at (3/2,-3) {3};

\draw [blue, thick] 
    ($(7)+(0,1)$) -- 
    ($(8)+(-\sinOffset,-\cosOffset)$) -- 
    ($(9)+( \sinOffset,-\cosOffset)$) -- cycle;
\end{tikzpicture}
\end{document}

相关内容