3

I am drawing AVL trees using tikz. I have this code:

\documentclass{scrartcl}
\usepackage{tikz}
\usetikzlibrary{trees}

\begin{document}
\begin{center}
    \begin{tikzpicture}
    \node[circle,draw](z){19}
    child{node[circle,draw]{16}
    child{node[circle,draw]{11}}
    child{node[circle,draw]{17}}}
    child{node[circle,draw]{21}
    child{node[circle,draw]{20}}
    child{node[circle,draw]{26}}};
    \end{tikzpicture}
\end{center}
\end{document}

It should be a balanced AVL tree. The right child of the 16 should be 17 and the left child of the 21 should be 20. With the code I get this

enter image description here

As you can see the 17 and the 20 are fused as one node. How can I solve this problem without modifying all other trees that I have drawn already?

Thanks for your answers!

2 Answers 2

6

You can specify a sibling distance for each level.

\documentclass{scrartcl}
\usepackage{tikz}
\usetikzlibrary{trees}

\begin{document}
    \begin{center}
        \begin{tikzpicture}[
                every node/.style={circle, draw},
                level 1/.style={sibling distance=6em},
                level 2/.style={sibling distance=3em},
            ]
            \node (z){19}
            child{node {16}
                child{node {11}}
                child{node {17}}}
            child{node {21}
                child{node {20}}
                child{node {26}}};
        \end{tikzpicture}
    \end{center}
\end{document}

enter image description here

I have also added a style for every node, which cleans up your code.

3

With use of the forest package the tree code is simpler and nodes never overlap:

\documentclass{scrartcl}
\usepackage{forest}

\begin{document}
\begin{center}
    \begin{forest}
for tree = {
% nodes
    circle, draw,
    minimum size = 2em,
    inner sep = 2pt, 
% tree
    grow = south,
    l sep = 9mm,  % vertical distances between nodes
    s sep = 3mm   % horizontal distances between nodes 
           }
[19
    [16
        [11]
        [17]
    ]
    [21 
        [20]
        [26]
    ];
]
    \end{forest}
\end{center}
\end{document}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .