Drawing a binary tree in pic

Last-Updated: 2026-09-02

Sources

A macro shared on the groff mailing list

This pic macro was written by Douglas McIlroy (2026-09/msg00003) and helps drawing a binary tree in only one line. He also wrote a document using this pic macro (doug/tree.pic) which you can turn in a PDF with 'groff -Tpdf -p -ms tree.pic > tree.pdf'.

This document is also mirrored on this website (resources/tree.pic).

Pic macro

.PS
.\" Pic macros for drawing binary trees
.\" M. Douglas McIlroy, Aug 30, 2026
.\" A tree is defined functionally, as in
.\" this example.
.\"    node(            /\ 
.\"      leaf,         /  \
.\"      node(        /    \
.\"        leaf,           /\
.\"        leaf           /  \
.\"      )               /    \
.\"    )
.\"
.\" Full disclosure: in actual use, the newlines in
.\" the neatly indented expression above would cause
.\" pic to barf. The expression works when written
.\" this way:
.\" node(leaf,node(leaf,leaf))
.\" Leaves occur at various heights, spaced
.\" uniformly left-to-right, with horizontal
.\" separation treesep_h. Each nonleaf node
.\" is positioned horizontally halfway between
.\" the roots of its subtrees (S1 and S2), with 
.\" vertical separation treesep_v. The root
.\" of each subtree is named R.
treesep_h = 1
treesep_v = 1
define leaf { [ R: "" ] }
define node { [
S1: $1 
S2: $2 with .nw at S1.ne + (treesep_h,0)
R:  0.5 + (0,treesep_v) 
    line from R to S1.R 
    line from R to S2.R
] }
.PE
← Go back