美文网首页
109. Convert Sorted List to Bina

109. Convert Sorted List to Bina

作者: 羲牧 | 来源:发表于2020-05-29 23:32 被阅读0次

    将链表转化为平衡二叉查找树,和数组转化为平衡二叉查找树类似,思路比较清晰。

    关键点在于如何寻找链表的中点,运用了快慢指针。
    快指针每次走两步,慢指针每次走一步,当快指针走到最后一个节点时,慢指针刚好走了一半,也就是中间节点。

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def sortedListToBST(self, head: ListNode) -> TreeNode:
            if head is None:
                return head
            if head.next is None:
                return TreeNode(head.val)
            slow = head
            fast = head
            last = slow
            while fast.next and fast.next.next:
                last = slow
                slow = slow.next
                fast = fast.next.next
            fast = slow.next
            last.next = None
            root = TreeNode(slow.val)
            if head != slow:
                root.left = self.sortedListToBST(head)
            root.right = self.sortedListToBST(fast)
            return root
            
            
    

    相关文章

      网友评论

          本文标题:109. Convert Sorted List to Bina

          本文链接:https://www.haomeiwen.com/subject/bhpqzhtx.html