5

I'm trying to draw an AVL tree with TikZ. I got the basic tree structure covered, but I'm not sure how to draw the balance factor outside of the node (see picture below).

Any suggestions?

enter image description here

Torbjørn T.
  • 206,688

2 Answers2

8

One option is to add labels to the nodes in the tree, e.g.

\documentclass{standalone}
\usepackage{tikz}
\begin{document}

\begin{tikzpicture}[
   edge from parent path=
    {(\tikzparentnode.south) .. controls +(0,-.5) and +(0,.5)
                             .. (\tikzchildnode.north)},
   every node/.style={draw,circle},
   label distance=-1mm]
\node [label=330:$-1$]{50}
  child {node[label=330:$-1$] {10}}
  child {node[label=330:$0$] {20}
  child {node[label=330:$-1$] {10}}
  child {node[label=330:$-1$] {20}}
};
\end{tikzpicture}
\end{document}

enter image description here

Torbjørn T.
  • 206,688
3

Here's a (very late) forest solution just because I wanted to draw the curvy paths.

\documentclass[tikz,border=5pt]{standalone}
\usepackage{forest}

\begin{document}

\begin{forest}
  my label/.style={label={[label distance=-5pt, font=\sffamily]-45:#1}},
  for tree={
    circle,
    draw,
    font=\sffamily,
    parent anchor=south,
    edge path={
      \noexpand\path [draw, \forestoption{edge}] (!u.parent anchor) [out=-90,in=90] to (.child anchor)\forestoption{edge label};
    },
    child anchor=north,
  }
  [50, my label=-1
    [30, my label=-1
    [19, for tree={my label=0}
        [18]
        [21]
      ]
      [31, my label=0
      ]
    ]
    [60, for tree={my label=0}
      [59]
      [70]
    ]
  ]
\end{forest}

\end{document}

<code>forest</code> solution

cfr
  • 198,882