Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
# 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 sortedarrayToBST(self,array):
length=len(array)
if length==0:
return None
if length==1:
return TreeNode(array[0])
root=TreeNode(array[int(length/2)])
root.left=self.sortedarrayToBST(array[:int(length/2)])
root.right=self.sortedarrayToBST(array[int(length/2)+1:])
return root
def sortedListToBST(self, head):
"""
:type head: ListNode
:rtype: TreeNode
"""
array=[]
p=head
while p:
array.append(p.val) #把linkedlist转换成array,然后可以取值建tree
p=p.next
return self.sortedarrayToBST(array)