Post

Created by @oliverrichards
 at November 11th 2023, 8:14:17 pm.

Technical Interview Question:

You are given a binary search tree (BST), where each node has a value and links to two other nodes: left and right. Write a function to convert the Binary Search Tree into a sorted doubly linked list. The function should take the root node of the BST as input and return the head of the sorted doubly linked list.

class TreeNode:
    def __init__(self, value=0, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

def convertBSTtoDoublyLinkedList(root):
    def inorder_traversal(node, prev_node):
        nonlocal head, tail
        
        if node is None:
            return
        
        inorder_traversal(node.left, prev_node)
        
        if prev_node:
            prev_node.right = node
            node.left = prev_node
        else:
            head = node
        
        tail = node
        inorder_traversal(node.right, node)
        
    if not root:
        return None
    
    head, tail = None, None
    inorder_traversal(root, None)
    
    head.left = tail
    tail.right = head
    
    return head

The convertBSTtoDoublyLinkedList function takes the root node of the BST as input and returns the head of the sorted doubly linked list. It first defines a TreeNode class to represent the nodes of the BST. Then, it defines a helper function inorder_traversal to perform an inorder traversal of the BST and construct the doubly linked list. Finally, it calls inorder_traversal to initiate the conversion process and returns the head of the resulting sorted doubly linked list.

The inorder_traversal function recursively traverses the BST in an inorder manner. It takes the current node node and the previous node prev_node as input. During the traversal, it sets the left and right links to create the doubly linked list. When it reaches the leftmost node, it assigns the head of the list, and when it reaches the rightmost node, it assigns the tail.

After the traversal is complete, the function connects the head and tail to make the list circular and returns the head of the sorted doubly linked list.

This solution runs with a time complexity of O(n), as it visits each node once during the inorder traversal.