As programmer,
your job is to create algorithms that solve specific problems and you can't rely on someone else to eternally do it for you, so there is a time where you will have to learn how to. And the sooner, the better.
When you just ask for the solution, it is like trying to learn to drive a car by having someone else training.
Creating an algorithm is basically finding the maths and make necessary adaptation to fit your actual problem.
Not a full blow up solution, But guidelines:
You want to render a binary tree as a 2D drawing on console with root on left and leafs on right.
Fact that impact the drawing:
-Console drawing imply integer coordinates
Questions to answer in order to draw the tree:
- My tree can be the root alone, how do I draw it?
- A binary tree is not limited to 7 nodes, your program must handle more or less nodes.
- The binary tree can be not full, some parents can have only 1 child either on left or right.
- The tree can be not equilibrated, some leaf can be on different levels.
- presentation: you must be able to handle the minimum spacing between nodes horizontally and vertically.
- Using
/ and
\ may be complicated to use as the orientation may not fit the drawing.
- You need to plan enough space between nodes everywhere to avoid collision of drawing lines and nodes.
- placing a new node can imply to move all parents nodes cascading to the root. If a non integer position arise, it will imply to move the sub-tree to correct the problem.
You will need to store nodes coordinates somewhere and probably an array of last used position per level
This graph editor will allow you to draw trees, it have the neat feature of spacing nodes to render your graph according to spacing rules.
yEd - Graph Editor[
^]
Note: with a sheet and pencil draw the tree starting with root only and draw how the tree rendering evolve as you add nodes. Do it with different trees until you are at ease with the placing processes.