写一个函数,输入一个非空的已排序的数组,数组的每个元素都是不一样的。根据这个数组构建一个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