一
import math
def print_tree(lis: list, unit_width=2):
n = len(lis) - 1
depth = math.ceil(math.log2(n + 1))
width = 2 ** depth - 1
index = 1
for i in range(depth):
width //= 2
pre = " " * (2 ** (4 - i) - 1) * unit_width
tree_str = lis[index:index + 2 ** i]
print(" " * width * unit_width, end="")
print(pre.join(map(lambda x: "{:{}}".format(x, unit_width), tree_str)))
index = index + 2 ** i
二
import math
'''
1.树深度公式
2.宽度=当前深度的满二叉树的所有节和叶的和
3.每个数的宽度
'''
lis = list(range(10, 20))
print(lis)
def print_tree(lis: list, unit_width=2):
n = len(lis) - 1
depth = math.ceil(math.log2(n + 1))
width = 2 ** depth - 1
index = 1
for i in range(depth):
for j in range(2 ** (i)):
tree_str = "{:^{}}".format(lis[index], width * unit_width)
print(tree_str, end=" " * unit_width)
index += 1
if index > n:
break
width //= 2
print()
w = print_tree(lis)