简体   繁体   English

如何以这种方式在python中打印一棵树?

[英]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是的,我知道,我不应该使用 2 个数据结构

thanks in advance :)提前致谢 :)

If your tree is a binary tree, the second form can be obtained using the printBTree function here如果您的树是二叉树,则可以使用此处的 printBTree 函数获得第二种形式

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.通过实现特殊方法__repr__可以使用 print() 函数打印任何节点。

For example:例如:

print(myTree.root)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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