MediumLinked ListDivide and ConquerTreeBinary Search TreeBinary Tree

1 approach, code in every language

Problem description

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

After the pattern

Now solve one you haven't seen.

Balanced Index Tree From A Reading Chain is our own problem on the technique behind Convert Sorted List 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