简体   繁体   中英

how to print a tree in python in this way?

i'm trying to print a tree, the problem is that i cant find any other way than printing it in this way:

1
|__2
   |__3
      |__33
   |__4
|__22

but is there anyway to print it in this way

      1
     / \
    2  22
   / \
  3   4
  |
  33

here is my code i wrote

class treeNode:

    def __init__(self,data):
        self.data = data
        self.children = []
        self.parent = None
        self.nextSibling = None
        self.level = 0
        self.prevSibling = None

    def add_children(self,*child):
        for i in child:
            i.parent = self
            self.children.append(i)
            if len(self.children) > 1:
                self.children[-2].nextSibling = i

class Tree:

    def __init__(self,root:treeNode):
        self.root = root
        self.depth = 0

    def print_tree(self):
        print(self.root.data)
        kid = self.root.children[0]
        while (kid != self.root):
            kid.level_func()
            print("  " * (kid.level - 1) * 2 + "|" + "__",kid.data)
            if len(kid.children) == 0:
                while kid.parent:
                    if kid.nextSibling:
                        kid = kid.nextSibling
                        break
                    else:
                        kid = kid.parent
            else:
                kid = kid.children[0]

yes i know, i shouldnt have used 2 data structures

thanks in advance :)

If your tree is a binary tree, the second form can be obtained using the printBTree function here

for example:

              80
          ___/  \___
        50          90
     __/  \__      /
   10        60  85
  /  \      /  \
 5    30  55    70
        \
         35

You could try to make a variant of it for a tree with multiple children but you will quickly run out of horizontal space.

for those trees, the indented format is preferable, although you could make it look a little better:

class treeNode:

    ...
    
    # list of lines to print for this node and its descendants 

    def lines(self,indent="",indent2=""): # node indent, children indent
        result = [indent+str(self.data)]       # line for node data
        for last,child in enumerate(self.children,1-len(self.children)):
            lines=child.lines(indent2+"|__ ",indent2+["|   ","    "][last==0]))
            result.extend(lines)               # add descendant lines
        return result

    def __repr__(self):
        return "\n".join(self.lines())

By implementing the special method __repr__ any node can be printed using the print() function.

For example:

print(myTree.root)

1
|__ 2
|   |__ 6
|   |__ 7
|__ 3
|__ 4
|__ 5
    |__ 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM