python-树-Min_Height_BST-最矮二叉搜索树

写一个函数,输入一个非空的已排序的数组,数组的每个元素都是不一样的。根据这个数组构建一个BST。返回这个BST的根节点。

样例输入:

[1, 2, 5, 7, 10, 13, 14, 15, 22]

此时会得到以下这个BST

					10

					/	\

				2			14

			/		\		/		\

		1			5		13		15

						\					\

						7						22

显然此时根节点为10

于是,函数返回10

样例输出:

10

Solution

由于此时数组已经是排好序的,可以充分利用这个性质。先插入中间的数字,对于左右两边的数组也是如此,由此可以产生最小的树。

def minHeightBst(array):
    return construct_min_height_BST(array,None,0,len(array)-1)

def construct_min_height_BST(array, bst, startIdx, endIdx):
    if endIdx < startIdx:
        return
    mid_Idx = (startIdx+endIdx)//2
    value_to_add = array[mid_Idx]
    if bst is None:
        bst = BST(value_to_add)
    else:
        bst.insert(value_to_add)
    construct_min_height_BST(array,bst,startIdx,mid_Idx-1)
    construct_min_height_BST(array,bst, mid_Idx+1, endIdx)
    return bst

class BST:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

    def insert(self, value):
        if value < self.value:
            if self.left is None:
                self.left = BST(value)
            else:
                self.left.insert(value)
        else:
            if self.right is None:
                self.right = BST(value)
            else:
                self.right.insert(value)


test_array = [1, 2, 5, 7, 10, 13, 14, 15, 22]
print(minHeightBst(array = test_array).value)

输出

10
[Finished in 0.6s]

Time: O(n log(n))

Space:O(n)

n: length of the array

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值