思路分析:如果要把一个有序的整数数组放在二叉树中,那么所构造出来的二叉树必定也是一颗有序的二叉树。因此,取数组的中间元素作为根节点,将数组分成左右两部分,对数组的两部分用递归的方法分别构建左右子树。
class BitNode:
def __init__(self):
self.data = None
self.lchild = None
self.rchild = None
# 方法功能:把有序数组转换为二叉树
def arraytotree(array, start, end):
root = None
if end >= start:
root = BitNode()
mid = int((start+end+1)/2)
# 树的根节点为数组中间的元素
root.data = array[mid]
# 递归的用左半部分数组构造root的左子树
root.lchild = arraytotree(array, start, mid-1)
# 递归的用右半部分数组构造root的右子树
root.rchild = arraytotree(array, mid+1, end)
else:
root = None
return root
# 用中序遍历的方式打印出二叉树节点的内容
def printTreeMidOrder(root):
if root == None:
return
# 遍历root节点的左子树
if root.lchild != None:
printTreeMidOrder(root.lchild)
# 遍历root节点
print(root.data)
# 遍历root节点的右子树
if root.rchild != None:
printTreeMidOrder(root.rchild)
if __name__ == "__main__":
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("数组:")
i = 0
while i < len(array):
print(array[i], end=" ")
i += 1
print('\n')
print("转换成树的中序遍历为:")
root = arraytotree(array, 0, len(array)-1)
print(printTreeMidOrder(root), end=" ")