Convert Sorted Array to Binary Search Tree

Easy Topics Company Tags

Given a strictly increasing integer array nums, construct a height-balanced binary search tree containing each array value exactly once, and return its root.

A binary search tree has smaller values in every left subtree and larger values in every right subtree. A tree is height-balanced when, at every node, the heights of its left and right subtrees differ by at most one.

There may be several valid answers; return any of them. Example outputs use level-order traversal, with null for missing children and trailing nulls omitted.

Example 1:

Convert Sorted Array to Binary Search Tree, example 1: illustration of the example

Input: nums = [-2,0,4]

Output: [0,-2,4]

Explanation: Root 0 has left child -2 and right child 4. The values satisfy the search-tree ordering, and the two subtrees have equal height.

Example 2:

Convert Sorted Array to Binary Search Tree, example 2: illustration of the example

Input: nums = [2,6]

Output: [6,2]

Explanation: Root 6 with left child 2 is valid. Root 2 with right child 6 would also be accepted: both trees contain the same values and are height-balanced.

Example 3:

Convert Sorted Array to Binary Search Tree, example 3: illustration of the example

Input: nums = [-5]

Output: [-5]

Explanation: The single value becomes the root. A one-node tree is both a binary search tree and height-balanced.

Constraints:

  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums is strictly increasing.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.