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.
Inorder traversal of BST is an array sorted in ascending order.
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.
Last updated