Moses Wescombe
Moses Wescombe

Reputation: 49

How can I print an unorganized tree to the console in Python

I have an organised doubly linked node tree and I am trying to find a way to print it to the console in ASCII form. In this code I convert a string like: "ABC@@DE@@@F@@" I have managed to store it in a doubly linked tree. However I cannot think how I would print it out in either vertical or horizontal format:

                                        A
                                  /----   \
                                 F         B
                                / \      /   --\
                               @   @    D       C
                                      /  \     /  \
                                     @    E   @    @
                                         / \
                                        @   @

Or

      @
      /  
     C
    / \
    |  @ 
    |     @
    |    /
   B    E
  / \  / \
A     D   @
|      \                              
|       @
|   @    
 \ /      
  F
   \
    @

If you would like the code feel free to ask, however it is not very nice code and might not give any useful guidance.If I am missing something obvious please excuse as I have only learnt code at the start of this year and am still in high school. Thanks heaps!

EDIT Here is the code if you want it. I have not commented extremely well and I'm sorry so good luck :)

class node: #user never interacts with the node class
    def __init__(self, value = None): #Creates a node this directions to the next node
        self.value = value
        self.leftChild = None #Later these will be set as other objects
        self.rightChild = None
        self.leftParent = None
        self.rightParent = None

class node_control:
    def __init__(self):
        self.root = None

    def insert(self, value):
        if self.root != None:
            self._insert(value, self.root)
            return
        else:
            print("New root - None", value)
            self.root = node(value)        

    def _insert(self, value, cur_node):
        #Go down right side
        while cur_node.rightChild != None and cur_node.rightChild.value != "@":
            print("ran")
            cur_node = cur_node.rightChild

        #If no right child
        if cur_node.rightChild == None:
            print("New node on right - None", value, "-", cur_node.value)
            #Create new node
            cur_node.rightChild = node(value)
            cur_node.rightChild.leftParent = cur_node
            return

        #If there is a "@"
        else:
            #if cur_node.leftParent != None:
            rep = True

            while rep:
                print(cur_node.value)
                #Check left child

                if cur_node.leftChild == None: #--
                    print("New node - No left child", value, "-", cur_node.value)
                    rep = False
                    cur_node.leftChild = node(value)
                    cur_node.leftChild.rightParent = cur_node
                    return
                elif cur_node.leftChild.value == "@": #If left child is blocked
                    if cur_node.leftParent != None:
                        print("Left is blocked", value, "-", cur_node.value)
                        print("Parent: ", cur_node.leftParent.value)
                        cur_node = cur_node.leftParent
                        rep = True
                        continue
                    elif cur_node.rightParent != None:
                        cur_node = cur_node.rightParent.leftParent
                        rep = True
                        continue                        

                #Broken ------
                else: #Must have a non "@" value so go down that line
                    print("Left is clear, reset", value, "-", cur_node.leftChild.value)
                    self._insert(value, cur_node.leftChild)
                return



#---
tree = node_control()
#---

text_code = "ABC@@D@@F@GH@@I@@"
text_array = []

#Create string array
for item in range(len(text_code)):
    text_array.append(text_code[item])

print(text_array)
for char in text_array:
    tree.insert(char)
    print("\n\n\t\tNew tree\n\n")

pass

Upvotes: 0

Views: 1055

Answers (1)

ktzr
ktzr

Reputation: 1645

I have something that kind of works, I modified the print logic from here print binary tree level by level in python (possibly a duplicate)

To node add:

def hight(self):
    if self.leftChild and self.rightChild:
        return 1 + max(self.leftChild.hight(),self.leftChild.hight())
    elif self.leftChild:
        return 1 + self.leftChild.hight()
    elif self.rightChild:
        return 1 + self.leftChild.hight()
    else:
        return 0

def __str__(self):
    return str(self.value)

To node_control add:

def print_tree(self):
    current_level = [self.root]
    offset = ' '*2**(self.root.hight())
    while current_level:
        nextlevel = list()
        offset = offset[:len(offset) // 2] # if python 2 just use 1 / 
        for n in current_level:
            print(offset + str(n.value),end="")
            if n.leftChild:
                nextlevel.append(n.leftChild)
            if n.rightChild:
                nextlevel.append(n.rightChild)
        print()
        current_level = nextlevel

tree.print_tree() outputs this:

        A
    F    B
  G  @  D  C
 I H @ @ @ @
@@@@

Upvotes: 1

Related Questions