因为Python列表中的元素可以是列表,所以可以使用列表构建树形结构。
构建指定层数的满二叉树:
def build_tree_depth(tree, n, m, data):#data是结点的数据,构造指定层数的满二叉树
#控制层数
if n == m - 1:
tree.append(data)
return data
else:
tree.append(data)
tree.append([])#创建左子树
data += 1#改变结点的值(这里只是一个实例而已)
data = build_tree_depth(tree[1], n+1, m, data)#递归实现创建
tree.append([])#创建右子树
data += 1
data = build_tree_depth(tree[2], n+1, m, data)#递归实现创建
return data
if __name__ == '__main__':
tree = []
n = 0
m = 4
data = 0
build_tree_depth(tree, n, m, data)#n,m控制数的层数,data为结点的数据
print(tree)
[0, [1, [2, [3], [4]], [5, [6], [7]]], [8, [9, [10], [11]], [12, [13], [14]]]]
[Finished in 0.2s]
搜索满二叉树:
def search_tree_depth(tree, data):#深度优先遍历
data.append(tree[0])#data记录各个结点的数值
if len(tree) != 1:#递归实现
search_tree_depth(tree[1], data)
search_tree_depth(tree[2], data)
return 0
if __name__ == '__main__':
tree = []
n = 0
m = 4
data = 0
build_tree_depth(tree, n, m, data)#n,m控制数的层数,data为结点的数据
data_search = []
search_tree_depth(tree, data_search)
print(data_search)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[Finished in 0.2s]
搜索某一路径下的结点:
上面我们创建的二叉树如下:
我们希望得到路径:0,1,2之后的结点,或路径0,1之后的结点:
def search_leaf(tree, data, road, result):#搜索某一路径下的任意结点
road.append(tree[0])
if len(tree) != 1:
search_leaf(tree[1], data, road, result)
search_leaf(tree[2], data, road, result)
else:
if road[:len(data)] == data[:]:
result.append(tree[0])
del(road[-1])
return 0
del(road[-1])
return 0
if __name__ == '__main__':
tree = []
n = 0
m = 4
data = 0
build_tree_depth(tree, n, m, data)#n,m控制数的层数,data为结点的数据
data_search = []
search_tree_depth(tree, data_search)
data = [0, 1, 2]
road = []
result = []
search_leaf(tree, data, road, result)
print(result)
data = [0, 1]
road = []
result = []
search_leaf(tree, data, road, result)
print(result)
[3, 4]
[3, 4, 6, 7]
[Finished in 0.2s]