109.有序链表转换二叉搜索树

难度:中等
题目描述:
109.有序链表转换二叉搜索树_第1张图片
思路总结:链表没法直接获取中点下标了,该怎么办呢,武器库里又来了新兵器——快慢指针。
题解一:

# 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

题解一结果:
109.有序链表转换二叉搜索树_第2张图片

你可能感兴趣的:(朱滕威的面试之路)