This is a small binary tree printer written in pure C, requiring no includes. By default it prints the following:
I think that I shall never see
A graph more lovely than a tree.
-- Radia Perlman
O
=================
| |
O O
========= =========
| | | |
O O O O
===== ===== ===== =====
| | | | | | | |
O O O O O O O O
=== === === === === === === ===
| | | | | | | | | | | | | | | |
O O O O O O O O O O O O O O O O
The first two lines are from the start of the poem “Algorhyme” by Radia Perlman, the inventor of the spanning tree.
Source Code
Here’s the compacted source for the tree-printing program:
#define j int j t(j p){return 1<1?h=atoi(v[1]):0;j x[25]={285563184,1494092560,85463301,106508377,218961937,51645273,106497812,946803732,403116633,207163657,1494484746,335743501,89718797,1493899281,117791000,1867191316,1499027801,1499027801,1499027801,1499027801,660163660,403707160,118761817,186125325,1868126553};j i,n;for(i=0;i<25;++i){for(n=0;n<4;++n){pc(121-(0x7F&x[i]>>8*n),1);};};ptr(h);return 0;}
EDIT: The code for this was originally just shy of 1kb (934 bytes), but I’ve since been able to shrink it further, as well as remove the need to include any external libraries like stdio.h
or math.h
. The current iteration is 777 bytes, a size I don’t think I can shrink by much (but I thought that back when this was 2k : ) ).
How to Use
If you copy the prior code into a text file and run:
cc tree_print.c -o tp; ./tp
You can also change the height of the tree via command line argument. For example, you can print a tree of height 7 by running ./tp 10
. Passing in a height of 0 prints just the poem.
Commented Source
The expanded and commented code can be found here: https://github.com/lelandbatey/tiny_tree_printer
Why?
I wrote this because it’s fun. Also, as a properly-implemented successor to a really hacky version of this I created years ago when I barely understood programming.