二叉树写着玩的脚本
基本信息:
函数功能描述:
本函数用于将一个数组打印成易于观看的二叉树形状
请求参数:
Query
参数名称 | 是否必须 | 类型 | 示例 | 备注 |
---|---|---|---|---|
listOne | 否 | list of int | [0,1,2,3,4,5,6,7,8,9] |
示例:
输入:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
输出:
0
1 2
3 4 5 6
7 8 9 10 11 12 13 14
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
源码:
def judgePosition(length):
"""
根据位置判断此数据应该在二叉树的第几行、第几列
:param length:
:return:
"""
rows = 0
# get rows
while True:
if (2 ** (rows - 1)) <= length <= (2 ** rows - 1):
break
else:
rows += 1
# get cols
cols = length - 2 ** (rows - 1) + 1
return rows, cols
def binaryTreePrinter(listOne=None):
"""
打印列表为二叉树形状
:param listOne: 传入的列表
:return:
"""
rows = judgePosition(len(listOne))[0] # rows为总行数
count = 0
pre_row, pre_col = 0, 0 # 记录上一个数的行与列
for x in listOne:
count += 1 # 计数现在打印的是第几个数
x_row, x_col = judgePosition(count) # 计算出当前打印的数位于第几行,第几列
if x_row != pre_row: # 如果换行了,那么打印换行符
print('\n')
if x_col != 1: # 如果当前打印的数字不是本行第一个,则打印步长为2**(rows-x_row+1)-1
print(' ' * (2 ** (rows - x_row + 1) - 1), end='')
else:
print(' ' * ((2 ** (rows - x_row + 1) - 1) // 2), end='')
print('{0:2}'.format(x), end='')
pre_row, pre_col = x_row, x_col # 位置记录更新
if __name__ == '__main__':
n = 30
listOne = [_ for _ in range(n + 1)]
print(listOne)
binaryTreePrinter(listOne)