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 = (start+end+1)//2 # 树的根节点为数组中间的元素 root.data = arr[mid] print(root.data) # 递归的用左半部分数组构成 root 的左子树 root.lchild = arraytotree(arr,start,mid-1) # 递归地用右半部分数组构成 root 的右子树 root.rchild = arraytotree(arr,mid+1,end) else: root = None return root # 用中序遍历的方法打印出二叉树结点的内容 def printTreeMidOrder(root): if root == None: return None #遍历root结点的左子树 if root.lchild != None: printTreeMidOrder(root.lchild) #遍历root结点 print(root.data,end=' ') #先从左边遍历 #遍历 root 的右子树 if root.rchild != None: printTreeMidOrder(root.rchild) #前序遍历 def printTreePreOrder(root): if root == None: return None #遍历root结点 print(root.data,end=' ') #遍历root结点的左子树 if root.lchild != None: printTreeMidOrder(root.lchild) #遍历 root 的右子树 if root.rchild != None: printTreeMidOrder(root.rchild) #后序遍历 def printTreeAfterOrder(root): if root == None: return None #遍历root结点的左子树 if root.lchild != None: printTreeMidOrder(root.lchild) #遍历 root 的右子树 if root.rchild != None: printTreeMidOrder(root.rchild) #遍历root结点 print(root.data,end=' ') arr = [1,2,3,4,5,6,7,8,9,10] print("数组:",end='') i = 0 while i < len(arr): print(arr[i],end = ' ') i += 1 print() root = arraytotree(arr,0,len(arr)-1) print("转换成树的中序遍历为:",end='') printTreeMidOrder(root)