Convert Sorted List To Binary Search Tree

To solve this coding challenge, we need to convert a sorted singly linked list to a height-balanced binary search tree (BST).

Explanation

A height-balanced BST ensures that the depth of the two subtrees of every node never differs by more than 1. Given the sorted nature of the list, an in-order traversal of the BST should match the order of elements in the list. This means that the middle element of the list should be the root of the BST, the left half of the list should form the left subtree, and the right half should form the right subtree. To achieve this, we can use a recursive approach:
  1. Count the number of nodes in the list : This helps us determine the size of the BST.
  2. Recursively construct the BST :
    • Divide the list range into two halves.
    • The middle element of the current range becomes the root.
    • Recursively apply the same process to the left half for the left subtree.
    • Move the list's current head to the next element.
    • Recursively apply the process to the right half for the right subtree.

    Detailed Steps in Pseudocode

  3. Calculate the size of the linked list :
    • Traverse the linked list and count the number of elements.
  4. Recursive function to construct the BST :
    • Use two pointers/indices to define the current range of the list.
    • Find the middle of the current range.
    • Recursively construct the left subtree.
    • Assign the current list node's value to the tree node.
    • Move to the next list node.
    • Recursively construct the right subtree.
  5. Initialize :
    • Set the head of the linked list.
    • Start the recursive function with the full range of the list.

    Pseudocode

                                                
    # Define the ListNode and TreeNode as basic data structures
    class ListNode:
    def __init__(self, val, next=None):
    self.val = val
    self.next = next
    
    class TreeNode:
    def __init__(self, val=0, left=None, right=None):
    self.val = val
    self.left = left
    self.right = right
    
    # Main function to convert sorted list to BST
    function sortedListToBST(head):
    # Helper function to count the number of nodes in the list
    function countNodes(node):
    count = 0
    while node != null:
    count += 1
    node = node.next
    return count
    
    # Helper function to recursively convert list to BST
    function convertToBST(left, right):
    if left > right:
    return null
    mid = (left + right) // 2
    
    # Recursively form the left subtree
    leftChild = convertToBST(left, mid - 1)
    
    # Node to be the root
    root = TreeNode(head.val)
    root.left = leftChild
    
    # Move to the next list node
    head = head.next
    
    # Recursively form the right subtree
    root.right = convertToBST(mid + 1, right)
    
    return root
    
    size = countNodes(head)  # Calculate the size of the list
    return convertToBST(0, size - 1)  # Form the BST
    
                                            
    Step-by-Step Explanation of the Pseudocode:
  6. Initialization of ListNode and TreeNode Classes :
    • ListNode : Represents a node in the singly linked list with a value and a pointer to the next node.
    • TreeNode : Represents a node in the binary search tree with a value, a left child, and a right child.
  7. Main Function
    sortedListToBST(head)
    :
    • countNodes(node)
      function
      : Counts the total number of nodes in the linked list by traversing from the head to the end.
    • convertToBST(left, right)
      function
      : This recursive function constructs the BST:
      • Base Case : If the left index exceeds the right index, return
        null
        . This indicates that there is no more node to include in the current subtree.
      • Find the middle point : Calculate the middle index of the current range to decide the root of the current subtree.
      • Recursive Construction of Left Subtree : Call
        convertToBST
        for the left half of the current range.
      • Root Node Construction : Create a new
        TreeNode
        with the current value of
        head
        , set the left child to the result of the left subtree construction, and move the head to the next node.
      • Recursive Construction of Right Subtree : Call
        convertToBST
        for the right half of the current range and set the right child to the result.
    • Calculate List Size and Begin Conversion : Determine the size of the list, then call
      convertToBST
      with the full range of indices.
Using these detailed steps and thorough comments in the pseudocode, we can carefully convert the sorted linked list into a height-balanced binary search tree.