1 import math 2 3 # 树的分析 4 origin = [30, 20, 80, 40, 50, 10, 60, 70, 90] 5 length = len(origin) # 节点 9 6 h = math.ceil(math.log(length, 2)) # >3 所以深度为4 7 max_length = 2 ** (h - 1) # 满二叉树的叶子数 8 index = 2 ** h - 1 # 总节点数 15 9 o = origin + [0] * (index - length) 10 new_list = len(o) * [0] 11 12 # 计算空格 13 for i in range(1, h + 1): 14 times = 2 ** (i - 1) # 每一层的个数 15 index //= 2 16 count = 1 17 new_list = len(o) * [0] # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 18 for j in range(times - 1, times * 2 - 1): 19 if count > times*10:break 20 if count % 2 != 0: 21 new_list[index*count+(count-1)] = o[j] 22 count += 1 23 else: 24 count += 1 25 new_list[index*count+(count-1)] = o[j] 26 count += 1 27 # print(new_list) 28 for i in new_list: 29 print(' ', end='') if i == 0 else print(i,end='') 30 print() 31 32 # 打印中间数 33 origin = [30, 20, 80, 40, 50, 10, 60, 70, 90] 34 length = len(origin) # 节点 9 35 h = math.ceil(math.log(length, 2)) # >3 所以深度为4 36 index = 2 ** h - 1 # 满树的总节点数 15 37 38 for i in range(1,h+1): 39 times = 2 ** (i - 1) 40 for j in range(times - 1, times * 2 - 1): 41 if j >= length: break 42 # print(index) 43 print('{:^{}}'.format(origin[j], index*2),end='**'*1) 44 print() 45 index //= 2