我使用BFS从树中提取了一个列表
solution = [[6],[0,7],[None,3,None,8],[2,5,None,9],[1,None,4,None,None,None], [无,无,无,无]]
如何将其打印为水平树?
我试图用
打印它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='')
但它给出了
答案 0 :(得分:1)
我玩过,这就是结果
{HOW TO USE THE APP SETTINGS KEY HERE}
我基本上做的是用缺少的数据填充解决方案列表,以便每个下一个子列表的值比前一个子列表多两倍。对于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
个子列表中的每个j
个元素,i
和[i+1][2*j]
下都有值。然后我只使用ASCII艺术打印出结果,计算出所需的偏移和间距。这里的限制是你只能使用数字0-9,以免搞砸我的树。你必须找出自己解决问题的方法:)
哦,是的。输出看起来像这样(随意更改缺失值和空格的字符):
[i+1][2*j+1]