"""Definition of ListNodeclass ListNode(object): def __init__(self, val, next=None): self.val = val self.next = nextDefinition of TreeNode:class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None"""classSolution:""" @param head: The first node of linked list. @return: a tree node """defsortedListToBST(self,head):# write your code hereifhead==None:returnNoneifhead.next==None:new_node=TreeNode(head.val)returnnew_node# find middledummy=ListNode(0,None)dummy.next=headfast_node=dummyslow_node=dummywhilefast_node!=Noneandfast_node.next!=None:fast_node=fast_node.next.nextprev_node=slow_nodeslow_node=slow_node.next# create the middle nodemiddle_node=TreeNode(slow_node.val)middle_node.right=self.sortedListToBST(slow_node.next)prev_node.next=Nonemiddle_node.left=self.sortedListToBST(dummy.next)returnmiddle_node