8

How can one draw an unbalanced binary tree - with missing nodes using the forest package?

3 Answers 3

5

There are various things you might mean by 'missing nodes'. A Minimal Working Example of the kind of tree you have, together with an explanation of how you wish to adapt it would be invaluable.

The following example shows three things you might have in mind:

Missing nodes

Node 2 is missing in a first sense: the branch simply continues without stopping to make the node. This creates an 'unbalanced' tree - the angles of the left and right branches are different.

  • This effect is achieved by altering the distance of node 4's level using l*=2 which doubles it.

Node 6 is missing in a second sense: it is simply empty. It is treated in every way as a proper node but there is no content.

  • This is straightforward - {} just provides empty content.

Node 9 is missing in a third sense: it causes a gap in the entire structure of branches and nodes. This isolates its children, 17 and 18 from the remainder of the tree.

  • This uses .phantom style demonstrated in NightRa's answer.

The code:

\documentclass{standalone}
\usepackage{forest}

\begin{document}
\begin{forest}
  [1, for tree=draw
    [4, l*=2
      [7
        [13]
        [14]]
      [8
        [15]
        [16]]
    ]
    [3
      [5
        [,.phantom
          [17]
          [18]]
        [10
          [19]
          [20]]
      ]
      [{}
        [11
          [21]
          [22]]
        [12
          [23]
          [24]]
      ]
    ]
  ]
\end{forest}
\end{document}
8

Using forest, you can create a phantom element, which behaves as if there is an element there for layout, but isn't drawn.

Example:

\documentclass[a4paper]{article}
\usepackage{forest}

\begin{document}
\begin{forest}
for tree={circle,draw}
[9 
  [5
    [1]
    [,phantom]
  ]
  [7]
]
\end{forest}
\end{document}

Which renders:

Unbalanced binary tree render

0

Left skewed tree using forest:

  \begin{forest}
  label tree,
  for tree={
    circle,draw,
    s sep'=10pt, 
    edge+=thick,  
    font=\strut\footnotesize\sffamily,
  },
  [A, name=lvl0
    [B
      [C
        [D 
          [E
            [F][,phantom]
          ][,phantom]
        ][,phantom]
      ][,phantom]
    ][,phantom]
  ]
  \end{forest}

Right skewed tree using forest:

  \begin{forest}
  label tree,
  for tree={
    circle,draw,
    s sep'=10pt, 
    edge+=thick,  
    font=\strut\footnotesize\sffamily,
  },
  [A[,phantom]
    [B[,phantom]
      [C[,phantom]
        [D[,phantom] 
          [E
            [,phantom] [F]
          ]
        ]
      ]
    ]
  ]
  \end{forest}

Left and right skewed tree using forest

You must log in to answer this question.

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