leetcode summary: link list problem solved by extra space

143. Reorder List

link list ⇒ list

class Solution(object):
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: None Do not return anything, modify head in-place instead.
        """
        s=[]

        cur=head
        while cur:
            s.append(cur)
            cur=cur.next

        cnt=len(s)/2

        cur=head
        
        while cnt:
            node=s.pop()
            t=cur.next
            cur.next=node
            node.next=t

            cur=t
            cnt-=1

        if cur:
            cur.next=None
        return head

109. Convert Sorted List to Binary Search Tree

when not using extra space, we must seperate the link list again an again, find the middle node, then using recursive way to go on

class Solution(object):
    def sortedListToBST(self, head):
        """
        :type head: ListNode
        :rtype: TreeNode
        """
        def helper(s):
            l=s
            h=s
            last=l
            if not s:
                return None
            if not s.next:
                return TreeNode(s.val)

            while h.next and h.next.next:
                h=h.next.next
                last=l
                l=l.next
            
            if l==h:
                l=l.next
        
            last.next=None
            h=l.next
            
            node=TreeNode(l.val)
            
            node.left=helper(s)
            node.right=helper(h)
            return node

        return helper(head)

we can using extra space to store all the list values to a array, so it change to the problem: convert array to binary search tree

class Solution:

    # Convert the given linked list to an array
    def mapListToValues(self, head):
        vals = []
        while head:
            vals.append(head.val)
            head = head.next
        return vals    

    def sortedListToBST(self, head):
        """
        :type head: ListNode
        :rtype: TreeNode
        """

        # Form an array out of the given linked list and then
        # use the array to form the BST.
        values = self.mapListToValues(head)

        # l and r represent the start and end of the given array
        def convertListToBST(l, r):

            # Invalid case
            if l > r:
                return None

            # Middle element forms the root.
            mid = (l + r) // 2
            node = TreeNode(values[mid])

            # Base case for when there is only one element left in the array
            if l == r:
                return node

            # Recursively form BST on the two halves
            node.left = convertListToBST(l, mid - 1)
            node.right = convertListToBST(mid + 1, r)
            return node
        return convertListToBST(0, len(values) - 1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章