Here is how you can convert a sorted Single Linked List to a List. Then, convert that to a Binary Search Tree:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sortedListToBST(self, head):
"""
:type head: ListNode
:rtype: TreeNode
"""
sll_list = self.linkedListToList(head)
def convert(left, right):
if left > right:
return None
mid = (left + right) // 2
node = TreeNode(sll_list[mid])
node.left = convert(left, mid - 1)
node.right = convert(mid + 1, right)
return node
return convert(0, len(sll_list) - 1)
def linkedListToList(self, head):
if not head:
return []
pointer = head
sll_list = []
while pointer:
sll_list.append(pointer.val)
pointer = pointer.next
return sll_list