class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
def get_root(pointer):
if pointer is None:
return None
if pointer.next is None:
return TreeNode(pointer.val)
fast, slow, pre = pointer, pointer, None
while fast is not None and fast.next is not None:
fast = fast.next.next
pre = slow
slow = slow.next
root = TreeNode(slow.val)
pre.next = None # 切断左子链与后面的连接, 进入递归
root.left = get_root(pointer)
root.right = get_root(slow.next)
return root
return get_root(head)