简体   繁体   中英

Printing a 2d binary search tree in Python

So I want to write a function to print my binary tree like this:

              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. How can i print the tree using the breadth first method in python? I'm completly new to python and don't really know where/how to do it.

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:

           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):

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:

      _____10_____      
   __5___      __15__   
  *     *     *     20

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