AlgoMaster Logo

Convert Sorted List to Binary Search Tree

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Naive Approach: Convert List to Array

Intuition:

The simplest way to address this problem is to transform the sorted linked list into an array. Once in array form, the middle element of any subarray serves as the root for the Binary Search Tree (BST). By recursively applying this process to the left and right subarrays, we build the complete tree.

This method is straightforward as it leverages the property of arrays that allow O(1) element access. However, this comes with a storage cost since we need additional space for the array.

Steps:

  1. Convert the linked list into an array.
  2. Recursively build BST from the array’s middle elements:
    • Choose the middle of the current array segment as the root.
    • Recursively create left and right subtrees using the subarrays to the left and right of the middle element.

Code:

2. Optimized Approach: Inorder Simulation

Intuition:

Instead of first converting the linked list to an array, we can directly use the properties of the list and simulate an inorder traversal. By using the fast and slow pointer technique, we can find the middle element of the linked list and use it as the root. This method eliminates the need for extra space associated with array storage.

Steps:

  1. Use a helper function to recursively find and set the middle element of the list as the root.
  2. Use two pointers (fast and slow) to find the middle:
    • Move fast two steps and slow one step to maintain the alignment needed to find the middle.
  3. Recursively apply the same process to the left and right sublists.

Code: