Home > Back-end >  Print elements of a list into binary tree format
Print elements of a list into binary tree format

Time:02-17

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

  1. 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
  2. It is an exercise and I can't use another structures, only a list
  3. 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)

CodePudding user response:

numbers = [9, 4, 6, 5, 2, 3]

def format_numbers(numbers):
    out = []
    for n in numbers: 
        fn = str(n) if len(str(n)) > 1 else f"0{n}"
        out.append(fn)
    return out

numbers = format_numbers(numbers)

print(f"\n        {numbers[0]}")
print("      /    \\")
print(f"    {numbers[1]}      {numbers[2]}")
print("   /  \\    /  \\")
print(f"  {numbers[3]}  []  {numbers[4]}  {numbers[5]}")

CodePudding user response:

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 ,)

  • Related