关于上篇的二叉树保存方法
上篇中提到的保存二叉树的保存的第二种方法,在这里使用python进行实现。
详见二叉树的保存.
在程序中会用到math中的ceil函数去向上取整。先引入math库。
import math
建立一个tree类,设定他的内置变量列表tree。
class Tree:
def __init__(self):
self.tree = []
接下是分别获取树的获取以及读取的方法
def get_tree(self):
print('input your information')
while True:
temp = str(input()) #所有数据统一为str类型方便处理
if temp == '-1':
break #设置退出循环条件输入为-1
else:
self.tree.append(temp)
def return_tree(self): #目标是输出为用0将二叉树补为完全二叉树的形式输出
if not self.tree: #若tree没有值返回False
return False, "No information on 'self.tree'"
temp = [] # 每一列的内容
temp_twice = [] # 树中的每一列
zero_list_before = [] #处理中的前一行'0'所在的的位置
zero_list_now = [] #当前行'0'所在位置
row = 0 #处理的第几行
index = 1 #每一行每一个数据的下标
num_index = 1 #循环中tree的值对应的下标
while num_index <= len(self.tree):
num = self.tree[num_index - 1] #获取tree列表中要处理的数据
if index > 2 ** row: #每一行到最大值换行处理
index = 1
temp.append(temp_twice)
zero_list_before = zero_list_now
zero_list_now = []
temp_twice = []
row += 1
if num == '0': #若获取到空节点的处理
temp_twice.append(0)
zero_list_now.append(str(index))
index += 1
num_index += 1
elif str(math.ceil(index / 2)) in zero_list_before: #对空节点下的空节点进行处理
zero_list_before.pop(0)
for i in range(2):
temp_twice.append(0)
zero_list_now.append(str(index))
index += 1
else: #正常值的处理
temp_twice.append(num)
index += 1
num_index += 1
temp.append(temp_twice) #将最后且不完整的最后一行拼接到最后
return temp #返回获取到的以完全二叉树的列表
本文作者独立完成,若有雷同纯属巧合。未经作者同意禁止转载。