MediumLinked ListDivide and ConquerTreeBinary Search TreeBinary Tree

Convert Sorted List to Binary Search Tree

LeetCode
1 approach, code in all languages

You are given the head of a singly linked list whose values are sorted in ascending order. Construct and return a height-balanced binary search tree containing the same values.

As with the array version, a height-balanced tree keeps the left and right subtree heights within one of each other at every node. Any valid height-balanced BST is accepted.

Example 1

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

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

The middle value 0 anchors the root; the elements before it form the left subtree and those after form the right subtree, producing a balanced BST.

Example 2

Input: head = []

Output: []

An empty list corresponds to an empty tree.

Constraints

  • The number of nodes in head is in the range [0, 2 * 10^4].
  • -10^5 <= Node.val <= 10^5
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