算法:如何把一个有序整数数组放到二叉树中

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 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值