简体   繁体   English

在 Python 中打印二维二叉搜索树

[英]Printing a 2d binary search tree in Python

So I want to write a function to print my binary tree like this:所以我想写一个 function 来打印我的二叉树,如下所示:

              10
         5          15
     *     *     *     20

I have a function for breadth first order that prints an array in that order and sets '*' where the none nodes are.我有一个用于广度一阶的 function,它按该顺序打印一个数组,并在没有节点的位置设置“*”。 How can i print the tree using the breadth first method in python?如何使用 python 中的广度优先方法打印树? I'm completly new to python and don't really know where/how to do it.我对 python 完全陌生,我真的不知道在哪里/如何做。

For a simple implementation of printing a binary heap, you can get the width of the largest node value and use it to compute the total width of descendants for nodes at a given level.对于打印二进制堆的简单实现,您可以获得最大节点值的宽度,并使用它来计算给定级别节点的后代的总宽度。 Print nodes of each level centered in their respective descendant total width:每个级别的打印节点以它们各自的后代总宽度为中心:

tree = [10,5,15,'*','*','*',20]

width  = max(map(len,map(str,tree)))+1 # width of largest node value
height = len(tree).bit_length()        # height of tree
i,n = 0,1                              # node index, nodes at level
for r in range(height,0,-1):
    span = width*2**r                # width to center each node in
    for node in tree[i:i+n]:         # print level's nodes on same line
        print(str(node).center(span),end="")
    print()                          # new line
    i += n                           # index of first node on next level
    n *= 2                           # number of nodes on next level

Output: Output:

           10           
     5           15     
  *     *     *     20  

If you want to make it prettier, you can add underlines on each side of the nodes using.center() for half the node's span width (except on last level because leaf nodes have no descendants):如果你想让它更漂亮,你可以使用 .center() 在节点的每一侧添加下划线,作为节点跨度宽度的一半(最后一层除外,因为叶节点没有后代):

tree = [10,5,15,'*','*','*',20]

width  = max(map(len,map(str,tree)))+1 # width of largest node value
height = len(tree).bit_length()        # height of tree
i,n = 0,1                              # node index, nodes at level
for r in range(height,0,-1):
    span = width*2**r                # width to center each node in
    for node in tree[i:i+n]:         # print level's nodes on same line
        print(str(node).center(span//2," _"[r>1]).center(span),end="")
    print()                          # new line
    i += n                           # index of first node on next level
    n *= 2                           # number of nodes on next level

Output: Output:

      _____10_____      
   __5___      __15__   
  *     *     *     20

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

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