Print Tree

There are only two types of programmers; programmers who can print trees and who cannot.

Print Tree

I have spent a weekend writing a program to print a tree on the console. A tree printer is one of the programmers' favorite wheels to reinvent, isn't it? If you think it is a piece of cake, you should try it out by yourself. I am sure you will change your mind in an hour.

There are many ways to represent a tree with ASCII characters. For my weekend project, I decided my ASCII-tree shape to be something like the following.

Example input.
1 --- 2
   |- 3 --- 5
   |     |- 6
   |     |_ 7
   |_ 4
Example output.

The major observations are:

  • We can generate the whole string line by line by traversing all the nodes in pre-order.
  • We can categorize a node as one of the following: ROOT, FIRST, MIDDLE, or LAST.
  • Each line consists of several smaller parts.
Major components of lines.

Here is a step-by-step illustration of the program.

You can find my TypeScript implementation on Gist.