EasyArrayDivide and ConquerTreeBinary Search TreeBinary Tree

1 approach, code in every language

Problem description

You are given an integer array nums that is sorted in strictly ascending order. Build and return a height-balanced binary search tree from these values.

A height-balanced tree is one in which, for every node, the heights of its two subtrees differ by at most one. Multiple valid trees may exist for the same input; any height-balanced BST is accepted.

Example 1

Input: nums = [-10,-3,0,5,9]

Output: [0,-3,9,-10,null,5]

Choosing 0 (the middle element) as the root and recursing on the halves yields a balanced BST. Other balanced answers such as [0,-10,5,null,-3,null,9] are also valid.

Example 2

Input: nums = [1,3]

Output: [3,1]

With two elements, either 1 or 3 can serve as the root; both [3,1] and [1,null,3] are height-balanced.

Constraints

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

After the pattern

Now solve one you haven't seen.

Balanced Marker Index is our own problem on the technique behind Convert Sorted Array to Binary Search Tree: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free