23.3-习题打印树和二叉树遍历
2019-10-17 本文已影响0人
BeautifulSoulpy
成年人之间最好的关系,不是彼此给与,而是保持距离感;
好的关系,都有点冷淡!

练习1: 打印树
打印要求,严格对齐,不重叠,就像一颗二叉树一样;

# 思路1:计算间隔数实现
def print_tree(array, unit_width=2):
'''
i 前空格 元素间
3 7
2 3
1 1
0 0
'''
length = len(array)
index = 1
depth = math.ceil(math.log2(length)) #4
sep = ' '*unit_width
for i in range(depth-1,-1,-1):
pre = 2**i - 1
print(sep*pre,end='')
offset = 2 ** (depth - i - 1)
line = array[index: index+offset]
intervalspace = sep * (2*pre + 1)
print(intervalspace.join(map(str,line)))
index += offset
print_tree([0,30, 20, 80, 40, 50, 10, 60, 70, 90])
#----------------------------------------------------------------------
30
20 80
40 50 10 60
70 90
import math
def print_trees(array,unit_width=2):
length = len(array)
depth = math.ceil(math.log2(length+1))
index = 0
width = 2**depth -1 # 行宽度,最深的行15个数
for i in range(depth): # 0123
for j in range(2**i): # 计数
# 居中打印,后面追加一个空格
print('{:^{}}'.format(array[index],width*unit_width),end = ' '*unit_width)
index += 1
if index >= length:
break
width = width//2 # 居中打印宽度减半
print() #控制换行;
print_trees([x+1 for x in range(29)])
#----------------------------------------------------------------
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