very clean python recursive code(easy to understand)


  • -1
    L

    class Solution(object):
    def mergeKLists(self, lists):
    m = len(lists)
    if m == 0:
    return None
    if m == 1:
    return lists[0]
    node1 = self.mergeKLists(lists[:m/2])
    node2 = self.mergeKLists(lists[m/2:])
    return self.help(node1, node2)

    def help(self, node1, node2):
        dummy = ListNode(0)
        tem = dummy
        while node1 is not None and node2 is not None:
            if node1.val <= node2.val:
                tem.next = node1
                tem = node1
                node1 = node1.next
            else:
                tem.next = node2
                tem = node2
                node2 = node2.next
        if node1 is None:
            tem.next = node2
        if node2 is None:
            tem.next = node1
        return dummy.next

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.