Start learning free

LESSON 499 OF 671 · BINARY TREES

Convert Sorted Array to Binary Search Tree

Practice Divide and Conquer, O(n)

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.

Example 1

Input: nums = [-10,-3,0,5,9]
Output: [0,-10,5,nil,-3,nil,9]
Explanation: The root is the middle element, 0, and each half is built the same way.
When a part has an even length, the root is the left one of its two middle elements
(-10 for [-10,-3], 5 for [5,9]). [0,-3,9,-10,nil,5] is also height-balanced, but the
tests expect the tree above. They print it level by level, with -1 for a missing child:
0 -10 5 -1 -3 -1 9

Example 2

Input: nums = [1,3]
Output: [1,nil,3]
Explanation: The root is the left middle element, 1, and 3 is its right child.
[3,1] is also a height-balanced BST, but the tests expect [1,nil,3], printed as: 1 -1 3

Constraints

  • 1 <= len(nums) <= 104
  • -104 <= nums[i] <= 104
  • nums is sorted in a strictly increasing order.
STEP 1 OF 9
    Ctrl + Enter to check