leetcode 109. Convert Sorted List to Binary Search Tree (Python)

Leetcode 109. Convert Sorted List to Binary Search Tree (Python)

Related Topic

Depth-First-Search. Tree.

Description

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Sample I/O

Example 1

Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

Methodology

This question can be solved by Depth First Search. It is similar with question 108. Convert Sorted Array to Binary Search Tree.The difference is using linked list instead of array

To ensure the depth of two substrees of each node never differ by more than one. We will start to use the mid node as root recursively. This will ensure the number of left node and right node for each root is either equal or differ by 1. Since the the input is already sorted. It will be easy to build a binary search tree.

To find the mid node in linkedlist, we can use fast and slow pointer. Every time fast will move two steps and slow will move step

Code

def sortedListToBST(self, head: ListNode) -> TreeNode:
        if not head:
            return None
        if not head.next:
            return TreeNode(head.val)
        
        def findMid(head):
            slow = fast = head
            prev = None
            while fast and fast.next:
                prev = slow
                slow = slow.next
                fast = fast.next.next
            prev.next = None
            return slow
        
        mid = findMid(head)
        root = TreeNode(mid.val)
        root.left = self.sortedListToBST(head)
        root.right = self.sortedListToBST(mid.next)
        
        return root

BigO

We traversal all nodes of the input so it takes O(n) time complexity

Search

    Table of Contents