EasyArrayDivide and ConquerTreeBinary Search TreeBinary Tree

Convert Sorted Array to Binary Search Tree

LeetCode
1 approach, code in all languages

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.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now