Any idea how to print a tree like this?
2
/ \
/ \
/ \
/ \
7 5
/ \ \
/ \ \
2 6 9
/ \ /
5 8 4
Any idea how to print a tree like this?
2
/ \
/ \
/ \
/ \
7 5
/ \ \
/ \ \
2 6 9
/ \ /
5 8 4
The horizontal solution works well as you can use a pre-order depth-first search (as you've shown) to construct the tree from each subtree, which aligns nicely with the way the console outputs one row at a time.
The vertical solution is more difficult, because you need to know all of the nodes at the end of the tree to calculate the full width. Therefore, you need to analyse the tree, store the data and then begin plotting.
The other option, while maybe not so "elegant" (definition dependent), would be to use something like a curses library, in which the concepts of display columns and rows are interchangeable.