跳到主要内容

Convert Sorted Array to Binary Search Tree

描述

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

分析

二分法。

代码

# Convert Sorted Array to Binary Search Tree
# Binary method, time complexity O(n), space complexity O(logn)
class Solution:
def sortedArrayToBST(self, nums: list[int]) -> 'TreeNode':
return self._sortedArrayToBST(nums, 0, len(nums))

def _sortedArrayToBST(self, nums: list[int], begin: int, end: int) -> 'TreeNode':
length = end - begin
if length < 1: return None # termination condition

# three-way merge
mid = begin + length // 2
root = TreeNode(nums[mid])
root.left = self._sortedArrayToBST(nums, begin, mid)
root.right = self._sortedArrayToBST(nums, mid + 1, end)

return root

相关题目