如何画一棵左右都有树枝的水平树?

如何画一棵左右都有树枝的水平树?

我需要画树,但它们应该从根部向两侧延伸。TikZ 似乎是一个很好的解决方案,但不知道如何管理它。

答案1

关键是grow选择(参见第18.5.2 默认增长函数手册)。 一个小例子:

\documentclass{article}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}[level distance=10mm,sibling distance=10mm,every node/.style={fill=blue!30,circle,inner sep=5pt}
]
\node {0}
child[grow=left] {
child {node{10}} child {node{20}} child {node{30}}
}
child[grow=right] {
child {node{40}} child {node{50}} child {node{60}}
};
\end{tikzpicture}

\end{document}

在此处输入图片描述

可以使用edge from parent。如果需要将箭头添加到许多边,最好的办法是定义一种样式(如艾伦·芒恩在评论中建议):

\documentclass{article}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}[level distance=10mm,
  sibling distance=10mm,
  every node/.style={fill=blue!30,circle,inner sep=5pt},
  arrow/.style={edge from parent/.style={draw,-latex}}
]

\node {0}
child[grow=left] {
child {node{10}} child {node{20}} child[arrow] {node{30}}
}
child[grow=right] {
child {node{40}} child {node{50}} child[arrow] {node{60}}
};
\end{tikzpicture}

\end{document}

在此处输入图片描述

答案2

根据树的复杂程度,将两棵树放在一起可能更简单。以下是用于tikz-qtree绘制树的示例。

\documentclass{article}

\usepackage{tikz}
\usepackage{tikz-qtree}
\usetikzlibrary{trees} % this is to allow the fork right path

\begin{document}

\begin{tikzpicture}[level distance=1.25in,sibling distance=.25in,scale=.75]
\tikzset{edge from parent/.style= 
            {thick, draw,
                edge from parent fork right},every tree node/.style={draw,minimum width=1in,text width=1in, align=center},grow'=right}
\Tree 
    [. parent 
        [.{nice child0}
                [.{grandchild0-0 } ]
            [.{grandchild0-1 } ]
            [.{grandchild0-2 } ]
            [.{grandchild0-3 with a really long name } ]
        ]
        [.child1
                [.{grandchild1-0 } ]
            [.{grandchild1-1 } ]
            [.{grandchild1-2 } ]
        ] 
        [.child2 ]
        [.child3 ]
    ]
\begin{scope}
\tikzset{edge from parent/.style= 
            {thick, draw,
                edge from parent fork left},every tree node/.style={draw,minimum width=1in,text width=1in, align=center},grow'=left}

\Tree 
    [.\node[draw=none]{}; 
        [.{nice child0}
                [.{grandchild0-0 } ]
            [.{grandchild0-1 } ]
            [.{grandchild0-2 } ]
            [.{grandchild0-3 with a really long name } ]
        ]
        [.child1
                [.{grandchild1-0 } ]
            [.{grandchild1-1 } ]
            [.{grandchild1-2 } ]
        ] 
        [.child2 ]
        [.child3 ]
    ]

\end{scope}

\end{tikzpicture}
\end{document}

代码输出

相关内容