'Print elements of a list into binary tree format
I have this list:
numbers = [9,4,6,5,2,3]
I am wondering how can I print the elements of that list in this format:
09
/ \
04 06
/ \ / \
05 [] 02 03
The element that always misses is the right child of the root's left child, returning an empty list
[]In all cases the input list has 6 elements, that is, the tree has 3 levels (root + first level + second level)
I have seen another similar questions where the solution was given using Linked Lists or simple Nodes, but at this time I can only use a simple list
I have only tried printing all the elements like this:
for elem in numbers:
print(elem)
The problem I have is that I don't know how to print / and \ in a proper way
Additional information
- Yes, it is about hard-code it all. It can be a similar format, not necessarily the same number of spaces between the elements, etc
- It is an exercise and I can't use another structures, only a list
- There's no context since it is an exercise. It is about finding a way to get that results (print the elements of the list in that way)
Solution 1:[1]
list=[9,4,6,5,2,3]
print(f"""
{str(list[0]).zfill(2)}
/ \\
{str(list[1]).zfill(2)} {str(list[2]).zfill(2)}
/ \ / \\
{str(list[3]).zfill(2)} [] {str(list[4]).zfill(2)} {str(list[5]).zfill(2)}""")
Because you say you can only use list method , This is the solution (If format string is not allowed , just turn all { and } to ,)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Unknown1234 |
