具有不对称兄弟姐妹的 TikZtree

具有不对称兄弟姐妹的 TikZtree

有没有办法在 Ti 中定义(二叉)树Z 其中兄弟姐妹的两条线的斜率不同。

我想生成一棵具有以下外观的树,而无需单独定位每个节点。

具有不对称兄弟节点的树:

答案1

我发布这个答案是因为之前的答案(西娜·艾哈迈迪)不满足一个重要条件:兄弟姐妹的两条线的斜率不同


可定制代码:

我们定义一个新的命令\binary。它的语法如下:

\binary[slope left=<num>,slope right=<num>,height=<num>] (<node>) to (<node>) node {<text>} and (<node>) node {<text>};

它将给我们

在此处输入图片描述

请注意,height是来自A.north而不是来自A.south。需要改进。

设置为slope left=50,slope right=35,height=0.75给我们

\documentclass[tikz,margin=3mm]{standalone}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\def\binary[slope left=#1,slope right=#2,height=#3] (#4) to (#5) node #6 and (#7) node #8; {
    \node (#5) at ($(#4)+({180+#1}:{#3/cos(90-(#1))})$) {#6};
    \node (#7) at ($(#4)+({-#2}:{#3/cos(90-(#2))})$) {#8};
    \draw (#5.north)--(#4.south)--(#7.north);
}
\node (A) at (0,0) {A};
\binary[slope left=50,slope right=35,height=0.75] (A) to (1) node {1} and (B) node {B};
\binary[slope left=50,slope right=35,height=0.75] (B) to (2) node {2} and (C) node {C};
\binary[slope left=50,slope right=35,height=0.75] (C) to (3) node {3} and (D) node {D};
\binary[slope left=50,slope right=35,height=0.75] (D) to (4) node {4} and (E) node {E};
\binary[slope left=50,slope right=35,height=0.75] (E) to (5) node {5} and (F) node {F};
\end{tikzpicture}
\end{document}

在此处输入图片描述

可定制性较差的代码:

稍作\binary改变,所有节点的标签和节点名称现在都相同。

\documentclass[tikz,margin=3mm]{standalone}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\def\binary[slope left=#1,slope right=#2,height=#3] (#4) to (#5) and (#6); {
    \node (#5) at ($(#4)+({180+#1}:{#3/cos(90-(#1))})$) {#5};
    \node (#6) at ($(#4)+({-#2}:{#3/cos(90-(#2))})$) {#6};
    \draw (#5.north)--(#4.south)--(#6.north);
}
\node (A) at (0,0) {A};
\binary[slope left=50,slope right=35,height=0.75] (A) to (1) and (B);
\binary[slope left=50,slope right=35,height=0.75] (B) to (2) and (C);
\binary[slope left=50,slope right=35,height=0.75] (C) to (3) and (D);
\binary[slope left=50,slope right=35,height=0.75] (D) to (4) and (E);
\binary[slope left=50,slope right=35,height=0.75] (E) to (5) and (F);
\end{tikzpicture}
\end{document}

在此处输入图片描述

答案2

易于操作forest

\documentclass{article}
\usepackage[linguistics]{forest}
\begin{document}
\begin{forest}for tree={calign=fixed edge angles,
calign primary angle=-30,calign secondary angle=60,l=1.25cm}
[A [1] [B [2] [C [3] [D [4] [E [5] [F]]]]]]
\end{forest}
\end{document}

代码输出

答案3

您可以使用forest包。这是一个最小的工作示例:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{forest}

\begin{document}
\begin{forest}
[A
    [1][B
        [2][C
            [3][D
                [4][E]
                ]
            ]
        ]
    ]
]
\end{forest}
\end{document}

得出以下结果:

在此处输入图片描述

您可以找到更多示例这里

相关内容