难度:中等
题目描述:
思路总结:链表没法直接获取中点下标了,该怎么办呢,武器库里又来了新兵器——快慢指针。
题解一:
# 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
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
#思路:
if head:
#1.先找中间值(快慢指针)
slow, quick, pre = head, head, head
while quick != None and quick.next != None:
pre = slow
slow = slow.next
quick = quick.next.next
root = TreeNode(slow.val)
if head == slow:
return root
#2.分别递归传入两边。
pre.next = None
root.left = self.sortedListToBST(head)
root.right = self.sortedListToBST(slow.next)
return root