Convert Sorted List to Binary Search Tree

Convert Sorted List to Binary Search Tree

Leetcode Daily Challenge (11th March, 2023)

Problem Statement:-

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

Link: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/

Problem Explanation with examples:-

Example 1

Input: head = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.

Example 2

Input: head = []
Output: []
Explanation: Given linked list is empty (null pointer), so return null.

Constraints

  • The number of nodes in head is in the range [0, 2 * 10<sup>4</sup>].

  • -10<sup>5</sup> <= Node.val <= 10<sup>5</sup>

Intuition:-

  • Convert the linked list to an array so that we can access elements by index.

  • Now, we have to construct a BST from the array. We can do this by finding the middle element of the array and making it the root of the tree. Then, we can recursively do the same for the left and right subarrays.

  • What comes to mind when we talk about finding the middle element of an array? Binary Search! So, we can use binary search to find the middle element of the array and then recursively construct the left and right sub-trees.

Solution:-

  • Initialize an empty array arr.

  • Convert the linked list to an array by traversing the linked list and storing the values in an array.

  • Define a function constructBST(arr, start, end) which takes the array, start index, and end index as arguments.

  • Put a base case to check if start is greater than end. If yes, return None.

  • Find the middle element of the array by calculating mid = (start + end) / 2.

  • Create a new node with the value arr[mid].

  • Recursively call the function constructBST(arr, start, mid - 1) and assign the returned value to the left child of the node.

  • Recursively call the function constructBST(arr, mid + 1, end) and assign the returned value to the right child of the node.

  • Return the node.

  • Call the function constructBST(arr, 0, len(arr) - 1) and return the returned value.

Code:-

JAVA Solution

class Solution {
   public TreeNode sortedListToBST(ListNode head) {
       List<Integer> arr = new ArrayList<>();
       while(head != null){
           arr.add(head.val);
           head = head.next;
       }
       return constructBST(arr,0,arr.size()-1);
   }

   public TreeNode constructBST(List<Integer> arr, int start, int end){
       if(start > end){
           return null;
       }
       int mid = (start+end)/2;
       TreeNode node = new TreeNode(arr.get(mid));
       node.left = constructBST(arr,start,mid-1);
       node.right = constructBST(arr,mid+1,end);
       return node;
   }
}

Python Solution

class Solution:
    def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
        def constructBST(arr,start,end):
            if start > end:
                return None
            mid = (start+end)//2
            node = TreeNode(arr[mid])
            node.left = constructBST(arr,start,mid-1)
            node.right = constructBST(arr,mid+1,end)
            return node

        arr = []
        while head:
            arr.append(head.val)
            head = head.next

        return constructBST(arr,0,len(arr)-1)

Complexity Analysis:-

TIME:-

Time complexity is O(N), where N is the number of nodes in the linked list as we are traversing the linked list to create an array of size N. Then we are using binary search to create the BST which takes O(log N) time.

SPACE:-

Space complexity is O(N), where N is the number of nodes in the linked list as we are creating an array of size N to store the values of the linked list. Then we are using binary search to create the BST which takes O(log N) stack space.

References:-

Connect with me:-

Did you find this article valuable?

Support Leeting-LCS by becoming a sponsor. Any amount is appreciated!