如何在Python中将无组织树打印到控制台

时间:2018-05-12 00:02:45

标签: python printing tree nodes

我有一个有组织的双向链接节点树,我试图找到一种方法以ASCII格式将其打印到控制台。在这段代码中,我转换了一个字符串,如:"ABC@@DE@@@F@@"我已经设法将它存储在一个双向链接的树中。但是我无法想象如何以垂直或水平格式打印出来:

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

或者

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

如果您希望代码随意询问,但它不是很好的代码,可能不会给出任何有用的指导。如果我遗漏了一些明显的东西请原谅,因为我在今年年初只学过代码而且我还在上高中。      谢谢堆!

修改 如果你需要,这是代码。我没有评论得非常好,我很抱歉这么好运:))

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

1 个答案:

答案 0 :(得分:1)

我有一些有用的东西,我从这里修改了打印逻辑print binary tree level by level in python(可能是重复的)

node添加:

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)

node_control添加:

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()输出:

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