When learning a tree, it is often necessary to draw a logical storage structure on paper. Not only not environmental protection, but also trouble. Wrote a small tool to draw a binary tree Dtree (drawtree). Source code reference links below.
Let's get to the last picture
The tool is based on the terminal character Graphics library ncurses implementation, in fact, if not the Third-party library, can be achieved, but some restrictions and trouble.
General Linux distributions have ncurses (or curses) libraries, and Dtree tools use ncurses libraries to move cursors easily. If you do not use the Ncurses library, additional data structures are required to record characters that are currently present at each coordinate location.
There is also a ncurses library that provides COLS macro Smart Display the width of the current terminal, if you get the terminal width may be more cumbersome.
Note the way to implement this tool:
2 structures are known:
The storage node of the struct node general tree contains the left child domain, the right child domain, and the data field.
The struct Dnode adds the index field to the node structure, representing the index of the position corresponding to the two-fork tree.
The Config.h file defines some constants.
The maximum number of Dnode nodes Max_node can draw.
Leaf_margin the distance between adjacent dnode in the bottom layer of a tree.
Custom nouns:
Decrement factor: The distance between each node and sibling node is divided by the distance between the nodes of their children.
The basic idea of realization is this:
First, the node structure is converted into a dnode structure. Find the relationship between the first node of each layer and the index, take the first node of each layer as the reference for all the nodes of the layer, compute their coordinates, and calculate the relationship between each node and index according to the mathematical calculation. The decrement factor takes 2 and draws all the nodes.
Defects:
1. The painting between the nodes is relatively sparse, if the tree balance is poor, the number of paintings is smaller. The solution is to adjust the descending factor between each layer smaller, less than 2, and try to rotate the tree into a balanced tree.
2. Coordinate movement relies on the ncurses library, the solution: can be completely based on the space (") and newline (' \ n ') to move the coordinates, but the array needs to store the characters of each position, and the width of the display area can not be dynamically adapted.
Source code Download link
http://download.csdn.net/detail/karizhang/6668639