2015-05-18 89 views
0

我已提取使用BFS打印一個漂亮的樹

溶液樹列表= [[6],[0,7],[無,3,無,8],[2,5,無,9],[1,沒有,4,None,None,None],[None,None,None,None]

如何將它打印爲橫向樹?

Desired Output

我試圖用

def _print_tree(n=0,height,solution): 
    if n > height: 
     return 
    for j in range(len(solution[n])): 
     if solution[n][j]== None: 
       print(' ' * (2 ** (height - n + 1) - 1),end='')     
     else: 
       print(' ' * (2 ** (height - n + 1) - 1), end='') 
       print(' ',solution[n][j], end='') 

打印,但它給了

Output

回答

1

我玩耍了,這裏是結果

nonechar = 'N' 
spacechar = '_' 

solution = [[6], [0, 7], [None, 3, None, 8], [2, 5, None, 9], [1, None, 4, None, None, None], [None, None, None, 4],[None, 3]] 

for i in range(1, len(solution)): 
    for j in range(len(solution[i-1])): 
     if (solution[i-1][j] == None): 
      solution[i].insert(2*j, None) 
      solution[i].insert(2*j+1, None) 
N = len(solution[-1]) * 2 - 1 
offset = (N - 1)/2 
spacing = 0 
for i in range(len(solution)): 
    line = spacechar * int(offset) 
    for j in range(len(solution[i])): 
     if (solution[i][j] == None): 
      line += nonechar 
     else: 
      line += str(solution[i][j]) 
     if (j != len(solution[i]) - 1): 
      line += spacechar * int(spacing) 
    line += spacechar * int(offset) 
    print(line) 
    spacing = offset 
    offset = (offset - 1)/2 

我基本上做的是用缺少的數據填充解決方案列表,以便每個下一個子列表的值比前一個值多兩倍。對於i第一個子列表中的每個j第012個元素,都有[i+1][2*j][i+1][2*j+1]下的值。然後我使用ASCII藝術打印出結果,計算出所需的偏移量和間距。這裏的限制是,你只能使用數字0-9,以免搞亂我的樹。你必須找出解決方法,你自己:)

哦,是的。輸出看起來像這樣(隨意更改缺少值和空格的字符):

_______________________________________________________________6_______________________________________________________________ 
_______________________________0_______________________________________________________________7_______________________________ 
_______________N_______________________________3_______________________________N_______________________________8_______________ 
_______N_______________N_______________2_______________5_______________N_______________N_______________N_______________9_______ 
___N_______N_______N_______N_______1_______N_______4_______N_______N_______N_______N_______N_______N_______N_______N_______N___ 
_N___N___N___N___N___N___N___N___N___N___N___N___N___4___N___N___N___N___N___N___N___N___N___N___N___N___N___N___N___N___N___N_ 
N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_3_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N