0108. Convert Sorted Array to Binary Search Tree
Easy | Binary Search Tree + Inorder Traversal | 40 ms (98.49%), 16.1 MB (78.29%)
Last updated
Was this helpful?
Easy | Binary Search Tree + Inorder Traversal | 40 ms (98.49%), 16.1 MB (78.29%)
Last updated
Was this helpful?
Source: GitHub:
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.