我正在研究树问题Convert Sorted Array to Binary Search Tree - LeetCode
给定一个元素按升序排序的数组,将其转换为高度平衡的 BST。
对于这个问题,高度平衡二叉树被定义为一个二叉树,其中每个节点的两个子树的深度相差永远不会超过 1。
例子:
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
直观的 D&Q 解决方案是
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
"""
Runtime: 64 ms, faster than 84.45%
Memory Usage: 15.5 MB, less than 5.70%
"""
if len(nums) == 0: return None
#if len(nums) == 1: return TreeNode(nums[0])
mid = len(nums) // 2
root = TreeNode(nums[mid])
if len(nums) == 1: return root
if len(nums) > 1:
root.left = self.sortedArrayToBST(nums[:mid])
root.right = self.sortedArrayToBST(nums[mid+1:])
return root
mid设置为len(nums)//2或(low + high)//2
当阅读其他提交时,我发现
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
return self.buildBST(nums, 0, len(nums))
def buildBST(self, nums, left, right):
if right <= left:
return None
if right == left + 1:
return TreeNode(nums[left])
mid = left + (right - left) // 2
root = TreeNode(nums[mid])
root.left = self.buildBST(nums, left, mid)
root.right = self.buildBST(nums, mid + 1, right)
return root
mid 被设置为 mid = low + (high -low)//2
mid = low + (high -low)//2超过有(low + high)//2什么好处?
呼如林
陪伴而非守候
相关分类