1.如果把一个有序的整数数组放到二叉树中,那么构造出的二叉树必定是有序二叉树,所以,取数组中间元素作为节点,将数组分成左右两部分,对数组的两部分递归的方法分别构建左右子树
2.代码如下:
class BiTNode():
def __init__(self):
self.data = None
self.lchild = None
self.rchild = None
#把有序数组转换为二叉树
def arraytotree(arr,start,end):
root = None
if end >= start:
root = BiTNode()
mid = int((start + end + 1) / 2)
#数的根结点为数组中间元素
root.data = arr[mid]
#递归的用左半部分数组构造root左子树
root.lchild = arraytotree(arr,start,mid-1)
#递归的用右半部分数组构造root的右子树
root.rchild = arraytotree(arr,mid+1,end)
else:
return None
return root
#用中序遍历的方式打印出二叉树节点的内容
def printTreeMidOrder(root):
if root == None:
return
#遍历root节点的左子树
if root.lchild != None:
printTreeMidOrder(root.lchild)
print(root.data,end=' ')
if root.rchild != None:
printTreeMidOrder(root.rchild)
if __name__ == '__main__':
arr = [1,2,3,4,5,6,7,8,9,10]
print('数组:',end=' ')
for i in range(len(arr)):
print(arr[i],end=' ')
print()
root = arraytotree(arr,0,len(arr)-1)
print('转换成数的中序遍历为:')
printTreeMidOrder(root)
print()
结果:
数组: 1 2 3 4 5 6 7 8 9 10
转换成数的中序遍历为:
1 2 3 4 5 6 7 8 9 10