给定一个有序整数数组,元素各不相同且按升序排列,编写一个算法,创建一棵高度最小的二叉搜索树。
示例:
给定有序数组: [-10,-3,0,5,9],
一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
Python3代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
def helper(nums, left, right):
if left > right:
return None
mid = left + (right-left)//2
tn = TreeNode(nums[mid])
tn.left = helper(nums, left, mid-1)
tn.right = helper(nums, mid+1, right)
return tn
return helper(nums, 0, len(nums) - 1)
网友评论