0108. Convert Sorted Array to Binary Search Tree
Easy | Binary Search Tree + Inorder Traversal | 40 ms (98.49%), 16.1 MB (78.29%)
Source: LeetCode - Convert Sorted Array to Binary Search Tree GitHub: Solution / Performance
Given an integer array nums
where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
Based on the above understanding, the middle element in an array sorted in ascending order is the root of BST. Therefore, we can create a helper function to retrieve the middle element and recursively call itself to find the middle element in the left and right parts by boundary indexes (start and end).
Note that the termination of recursion is important.
If start > end, there are no elements for the subtree. Return None.
if start == end, there is only one element for the subtree. Return TreeNode.
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
#: (base case)
if len(nums) == 1: return TreeNode(nums[0])
if len(nums) == 2: return TreeNode(nums[0], None, TreeNode(nums[1]))
# ==================================================
# Binary Search Tree + Inorder Traversal =
# ==================================================
# time : O(n)
# space : O(n)
self.nums = nums
return self.subTree(0, len(nums) - 1)
def subTree(self, start: int, end: int) -> TreeNode:
if start > end: return None
if start == end: return TreeNode(self.nums[start])
mid = (start + end) // 2
node = TreeNode(self.nums[mid])
node.left = self.subTree(start, mid - 1)
node.right = self.subTree(mid + 1, end)
return node
Last updated
Was this helpful?