# Binary search tree in TikZ, explained

> How a binary search tree is drawn with TikZ child syntax: a level style that shrinks the sibling distance, plus missing-child and forest variations.

URL: https://www.labcanvas.com/tikz/examples/computer-science/binary-search-tree

Updated 2026-11-22. Original figure: Binary search tree, © Martin Thoma, MIT licence (licence text: https://www.labcanvas.com/tikz-library/credits.html#thoma), from https://github.com/MartinThoma/LaTeX-examples/blob/f9236c5fe5d47f19822fcb11097df27355562314/tikz/binary-search-tree/binary-search-tree.tex. Walkthrough and variations by LabCanvas; the variation code is CC0 1.0 (https://creativecommons.org/publicdomain/zero/1.0/). Pictures typeset with TeX Live 2026 and PGF 3.1.12. Category: [TikZ computer science examples](https://www.labcanvas.com/tikz/examples/computer-science).

## Quick answer

This figure draws a binary search tree with root 17: smaller keys to the left, larger to the right, five levels deep, each key in a grey circle. It is one TikZ tree, `\node {17} child { … } child { … };`, with nested `child` operations for the subtrees, and a single option makes it fit: `level/.style={sibling distance=70mm/#1}`, which spreads the children 70 mm apart at the first level, 35 mm at the second, about 23 mm at the third and so on. Nodes with only one child show the syntax’s blind spot: a lone child hangs straight down, so the drawing cannot tell a left child from a right one.

## The figure and its code

![A binary search tree of grey circles joined by thick lines: 17 at the top with children 9 and 19; 9 has children 3 and 11; 3 has −3 and 8; −3 has −4 and 2; 2 has a single child 2; 8 has a single child 6 with children 5 and 7; 11 has a single child 17, which has a single child 17; 19 has a single child 20.](https://www.labcanvas.com/tikz-snippets/fig-binary-search-tree/original.webp)

Copyright (c) 2012-2013 Martin Thoma, MIT licence (https://www.labcanvas.com/tikz-library/credits.html#thoma). The code below is exactly the library's file (pdfLaTeX); its first lines name the source and the licence, and the MIT licence asks that they stay with the code. Open it in the TikZ editor from the page: https://www.labcanvas.com/tikz/examples/computer-science/binary-search-tree

```latex
% Binary search tree
% Source: https://github.com/MartinThoma/LaTeX-examples/blob/f9236c5fe5d47f19822fcb11097df27355562314/tikz/binary-search-tree/binary-search-tree.tex
% Copyright (c) 2012-2013 Martin Thoma. MIT licence: https://github.com/MartinThoma/LaTeX-examples/blob/master/LICENSE
% The licence’s copyright and permission notice: https://www.labcanvas.com/tikz-library/credits.html
\documentclass{article}
\usepackage[pdftex,active,tightpage]{preview}
\setlength\PreviewBorder{2mm}

\usepackage{tikz}
\usetikzlibrary{arrows,positioning,calc}
\tikzstyle{vertex}=[draw,fill=black!15,circle,minimum size=18pt,inner sep=0pt]

\begin{document}
\begin{preview}
\begin{tikzpicture}[very thick,level/.style={sibling distance=70mm/#1}]
\node [vertex] (r){$17$}
  child {
    node [vertex] (a) {$9$}
    child {
      node [vertex] {$3$}
      child {
        node [vertex] {$-3$}
        child {node [vertex] {$-4$}}
        child {
            node [vertex] {$2$}
            child {
                node [vertex] {$2$}
            }
        }
      }
      child {
        node [vertex] {$8$}
        child {
            node [vertex] {$6$}
            child {
                node [vertex] {$5$}
            }
            child {
                node [vertex] {$7$}
            }
        }
      }
    }
    child {
      node [vertex] {$11$}
      child {
        node [vertex] {$17$}
          child {
            node [vertex] {$17$}
          }
      }
    }
  }
  child {
    node [vertex] {$19$}
    child {
      node [vertex] {$20$}
    }
  };
\end{tikzpicture}
\end{preview}
\end{document}
```

## A cropped article and a node style

*Lines 5–11 of the code.*

The file uses the `article` class with the `preview` package: `active` and `tightpage` make each `preview` environment its own page, cropped to its content, and `\setlength\PreviewBorder{2mm}` adds a 2 mm margin. That is the older way to get a picture-sized PDF; `\documentclass{standalone}` does the same today. Line 10 loads three libraries the drawing never uses, including the deprecated `arrows`.

`\tikzstyle{vertex}=[draw,fill=black!15,circle,minimum size=18pt,inner sep=0pt]` defines the node style in the older syntax; current code writes `\tikzset{vertex/.style={…}}`. The style draws a grey circle of at least 18pt with no inner padding, so one- and two-digit keys get circles of the same size.

## One style that spaces the whole tree

*Lines 14–15 of the code.*

The picture options are `very thick`, which thickens the edges, and `level/.style={sibling distance=70mm/#1}`. TikZ runs the `level` style at the start of each set of children and passes the current level as #1, so the distance between siblings is 70 mm at level 1, 35 mm at level 2, 23.3 mm at level 3, 17.5 mm at level 4 and 14 mm at level 5. Shrinking the spread with depth is what keeps the subtrees from running into each other; a constant sibling distance would make the lower levels collide. Dividing by 2 at each level, `70mm/2^(#1-1)`, would give the classic halving used in the first variation. The vertical gap is the default `level distance`, 15 mm.

## The root and the left subtree

*Lines 16–53 of the code.*

The tree is a single path: `\node [vertex] (r){$17$}` followed by `child { … }` operations, each containing a `node` and, inside it, that node’s own children. The indentation mirrors the tree: 9 and its subtree, then 3 with −3 and 8, then the bottom levels. TikZ draws an edge from each parent to each child automatically. Only the root and the 9 node are named, `(r)` and `(a)`, and nothing refers to the names; they would be useful for drawing extra arrows or highlights on top of the tree.

The keys are typeset in maths mode, `{$-3$}`, so the minus sign is a real minus rather than a hyphen.

## The right subtree, and the single-child problem

*Lines 54–59 of the code.*

The right subtree is 19 with one child, 20. In a binary search tree, 20 is the *right* child of 19 because it is larger, but with a single `child` TikZ places it straight below its parent, exactly where a left child would also go. The same happens elsewhere in the figure: 6 is the left child of 8, the 17 under 11 is a right child, yet all of them hang vertically. The fix is `child[missing]`, an empty child that counts for the layout but is not drawn: `child[missing] child { node {20} }` pushes 20 to the right. The first variation does exactly that. The final `};` ends the path that began with the root.

## Techniques used

- [Trees with child](https://www.labcanvas.com/tikz/trees): nested `child { node {…} … }` operations, with edges drawn automatically.
- [Level styles](https://www.labcanvas.com/tikz/trees): `level/.style={sibling distance=70mm/#1}` receives the level number and shrinks the spread.
- [Node styles](https://www.labcanvas.com/tikz/nodes): one `vertex` style for every circle, in the older `\tikzstyle` form and the current `/.style` form.
- [Graphs and trees](https://www.labcanvas.com/tikz/graphs): trees as one kind of graph drawing in TikZ.

## Variations

Our own code, CC0 1.0, each typeset with TeX Live 2026 in a standalone document with the preamble lines shown.

### Left and right children with child[missing]

A binary search tree where every lone child sits on its correct side. Each node with one child gets a `child[missing]` on the other side, which keeps the slot empty. The spacing halves at each level, `sibling distance=48mm/2^(#1-1)`, so the slots of a full binary tree are evenly spread, and `edge from parent/.style` sets the edges in one place.

![A binary search tree: 50 at the top with children 30 and 70; 30 has children 20 and 40; 20 has only a right child 25; 40 has only a left child 35; 70 has only a right child 80; 80 has only a left child 75.](https://www.labcanvas.com/tikz-snippets/fig-binary-search-tree/missing-children.webp)

*a binary search tree with lone children on their correct side, using child[missing]*

Preamble: `\usepackage{tikz}`

```latex
\begin{tikzpicture}[
    vertex/.style={draw, circle, fill=gray!15, minimum size=7mm, inner sep=0pt, font=\small},
    level distance=12mm,
    % halve the spread at every level: 48, 24, 12 mm
    level/.style={sibling distance=48mm/2^(#1-1)},
    edge from parent/.style={draw, thick},
  ]
  \node[vertex] {50}
    child { node[vertex] {30}
      child { node[vertex] {20}
        child[missing]                      % 20 has no left child ...
        child { node[vertex] {25} } }       % ... and 25 is its right child
      child { node[vertex] {40}
        child { node[vertex] {35} }
        child[missing] } }
    child { node[vertex] {70}
      child[missing]
      child { node[vertex] {80}
        child { node[vertex] {75} }
        child[missing] } };
\end{tikzpicture}
```

### The same tree with forest

The forest package computes the layout itself and packs subtrees as tightly as their contents allow. The tree is written in bracket notation, `[50 [30 …] [70 …]]`; `for tree={…}` styles every node, `l sep` and `s sep` set the minimum gaps between levels and siblings, and an empty node with the `phantom` option, `[,phantom]`, keeps the empty side of a lone child.

![The same binary search tree drawn more compactly: 50 at the top, 30 and 70 below, 20 and 40 under 30, 25 to the right below 20, 35 to the left below 40, 80 to the right below 70 and 75 to the left below 80.](https://www.labcanvas.com/tikz-snippets/fig-binary-search-tree/forest.webp)

*the same binary search tree in forest’s bracket notation, laid out automatically*

Preamble: `\usepackage{tikz}`, `\usepackage{forest}`

```latex
\begin{forest}
  for tree={circle, draw, thick, fill=gray!15, minimum size=7mm, inner sep=0pt,
            font=\small, l sep=5mm, s sep=6mm},
  % bracket notation: [node [left child] [right child]]; phantom keeps an empty side
  [50
    [30 [20 [,phantom] [25]] [40 [35] [,phantom]]]
    [70 [,phantom] [80 [75] [,phantom]]]
  ]
\end{forest}
```

## Frequently asked questions

### How do I draw a binary tree in TikZ?

Start with a node and add children: \node {50} child { node {30} } child { node {70} };. Give the picture level/.style={sibling distance=40mm/#1} so the lower levels do not overlap, and use child[missing] for an empty left or right slot.

### Why do my TikZ tree nodes overlap?

sibling distance is the same at every level unless you change it. Make it depend on the level, level/.style={sibling distance=60mm/#1}, or use the forest package, which spaces the nodes automatically.

### How do I show that a single child is a right child?

Add an empty child before it: child[missing] child { node {20} }. The missing child takes the left slot without being drawn.

## References

- [MartinThoma/LaTeX-examples at commit f9236c5: tikz/binary-search-tree/binary-search-tree.tex (MIT licence)](https://github.com/MartinThoma/LaTeX-examples/blob/f9236c5fe5d47f19822fcb11097df27355562314/tikz/binary-search-tree/binary-search-tree.tex)
- [PGF/TikZ manual, §21 Making Trees Grow (child, level distance, sibling distance, grow)](https://tikz.dev/tikz-trees)
- [PGF/TikZ manual, §21.4 Specifying Options for Trees and Children (level styles)](https://tikz.dev/tikz-trees#sec-21.4)
- [PGF/TikZ manual, §21.5 Placing Child Nodes (missing children)](https://tikz.dev/tikz-trees#sec-21.5)
- [PGF/TikZ manual, §21.6 Edges From the Parent Node](https://tikz.dev/tikz-trees#sec-21.6)
- [PGF/TikZ manual, §12.4.2 Using Styles to Manage How Pictures Look](https://tikz.dev/tikz-scopes#sec-12.4.2)
- [forest 2.1.5 on CTAN (manual: forest-doc.pdf)](https://ctan.org/pkg/forest)
- [preview package on CTAN (active, tightpage, \PreviewBorder)](https://ctan.org/pkg/preview)

## TikZ guides for these techniques

- [TikZ trees: child syntax, forest and tikz-qtree](https://www.labcanvas.com/tikz/trees): Draw trees in LaTeX: TikZ child syntax with level and sibling distance, forest for automatic spacing, tikz-qtree, org charts, binary and decision trees.
- [TikZ graphs: drawing networks of vertices and edges](https://www.labcanvas.com/tikz/graphs): Graph theory drawings in TikZ: vertices and edges by hand, directed and weighted graphs, loops, the \graph syntax, K_n and C_n, and automatic layouts.
- [TikZ nodes: shapes, anchors, positioning and labels](https://www.labcanvas.com/tikz/nodes): How TikZ nodes work: shapes, size (inner sep, minimum size), all anchors, the positioning library (right=of, node distance), labels, pins and scaling.
