# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None
classSolution: defsortedListToBST(self, head: ListNode) -> TreeNode: if head isNone: returnNone if head.nextisNone: return TreeNode(head.val) slow = ListNode(-1) slow.next = head fast = head while fast isnotNone: last = slow slow = slow.next fast = fast.next.nextif fast.nextisnotNoneelseNone last.next = None right = slow.next slow.next = None root = TreeNode(slow.val) if slow isnot head: root.left = self.sortedListToBST(head) root.right = self.sortedListToBST(right) return root