有序数组转换为平衡二叉搜索树
2021-04-30 10:27
标签:复杂 list roo val python 思想 sorted 空间 转换 递归思想 有序数组转换为平衡二叉搜索树 标签:复杂 list roo val python 思想 sorted 空间 转换 原文地址:https://www.cnblogs.com/gugu-da/p/13229465.html将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树
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(left,right):
if left>right:
return None
mid = (left+right+1)//2
root = TreeNode(nums[mid])
root.left = helper(left,mid-1)
root.right = helper(mid+1,right)
return root
return helper(0,len(nums)-1)