import random
import math
def tree_depth(li):
depth = int(math.log2(len(li) + 1)) + 1
return depth
def print_line(string, fillchar, totlen, align_way):
if align_way == 0:
print("{0:{1}^{2}}".format(string, fillchar, totlen))
elif align_way == -1:
print("{0:{1}<{2}}".format(string, fillchar, totlen))
elif align_way == 1:
print("{0:{1}>{2}}".format(string, fillchar, totlen))
def printf_tree(li):
depth = tree_depth(li)
before = 0
align_way = 0
for i in range(depth):
thisline = ""
if i == depth - 1:
align_way = -1
for j in range(pow(2, i)):
try:
thisline = thisline + str(li[before + j]) + " "
except IndexError:
break
thisline = thisline[:-1:]
print_line(thisline, " ", pow(2, depth - 1) * 2 - 1, align_way)
before += pow(2, i)
def judge(li, cur_pos):
if (cur_pos * 2 + 1 > len(li) - 1 or li[cur_pos] > li[cur_pos * 2 + 1]) and (
cur_pos * 2 + 2 > len(li) - 1 or li[cur_pos] > li[cur_pos * 2 + 2]
):
return True
return False
def tree_judge(li):
for i in range(len(li) - 1, 0):
if li[i] > li[int(i - 1) // 2]:
return False
return True
def single_adjust(li, inode):
cur_pos = inode
if judge(li, cur_pos) == False:
if cur_pos * 2 + 2 > len(li) - 1:
li[cur_pos], li[cur_pos * 2 + 1] = li[cur_pos * 2 + 1], li[cur_pos]
cur_pos = cur_pos * 2 + 1
elif li[cur_pos * 2 + 2] > li[cur_pos * 2 + 1]:
li[cur_pos], li[cur_pos * 2 + 2] = li[cur_pos * 2 + 2], li[cur_pos]
cur_pos = cur_pos * 2 + 2
else:
li[cur_pos], li[cur_pos * 2 + 1] = li[cur_pos * 2 + 1], li[cur_pos]
cur_pos = cur_pos * 2 + 1
single_adjust(li, cur_pos)
def total_adjust(li):
for i in range(len(li) - 1, -1, -1):
single_adjust(li, i)
def tree2list(treeli, resultli):
original_list = treeli
while original_list:
resultli.append(original_list[0])
original_list[0] = original_list[-1]
del original_list[-1]
single_adjust(original_list, 0)
n = int(input("input tree node number:"))
testtree = [x for x in range(n)]
random.shuffle(testtree)
result_list = []
total_adjust(testtree)
printf_tree(testtree)
tree2list(testtree, result_list)
print(result_list)