Convert Sorted List to Binary Search Tree - Problem

Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced binary search tree.

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than 1.

The resulting BST should maintain the sorted order property where for each node:

  • All values in the left subtree are less than the node's value
  • All values in the right subtree are greater than the node's value

Input & Output

Example 1 — Basic Conversion
$ Input: head = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
💡 Note: One possible balanced BST: root=0, left subtree has -3 with -10 as left child, right subtree has 9 with 5 as left child
Example 2 — Empty List
$ Input: head = []
Output: []
💡 Note: Empty linked list results in null tree
Example 3 — Single Node
$ Input: head = [1]
Output: [1]
💡 Note: Single node becomes the root with no children

Constraints

  • 0 ≤ Number of nodes ≤ 2 × 104
  • -105 ≤ Node.val ≤ 105
  • The linked list is sorted in ascending order

Visualization

Tap to expand
INPUTALGORITHMRESULTSorted Linked List-10-3059Values: [-10, -3, 0, 5, 9]Length: 5 nodes1Find middle element2Make it root node3Build left subtree4Build right subtreeDivide & ConquerSplit: [−10,−3] | 0 | [5,9]Root: 0Recursively balanceHeight-Balanced BST0-39-105Balanced PropertyHeight difference ≤ 1Key Insight:Choose the middle element as root to ensure height balance. Recursively apply this to left and right sublists.TutorialsPoint - Convert Sorted List to BST | Divide & Conquer
Asked in
Facebook 15 Amazon 12 Microsoft 8 Google 6
125.0K Views
Medium Frequency
~25 min Avg. Time
4.6K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen