Why my recursive solution in Python got runtime error

  • 1

    Followings are the code I submit:

    def removeElements(self, head, val):
        if not head:
            return head
        head.next = self.removeElements(head.next, val)
        return head.next if head.val == val else head

    I test the code in my computer, and it is fine.
    But when I submit, I got runtime error:

    Line 14: File "/usr/lib/gcc/x86_64-linux-gnu/4.9.1/.cache/prog_join

    for the [1,9,9,9............9], 1 case.
    And I can't find the reason.
    Could somebody give a hint?

  • 0
    def removeElements(self, head, val):
            first = temp = ListNode(0)
            while head:
                head_val = head.val
                head = head.next
                if head_val == val:
                temp.next = ListNode(head_val)
                temp = temp.next
            return first.next

    i don't know why ...
    but i can run true in my local system

  • 0

    i can run in my local system...

  • 0

    I'm getting the same error on the same test case. I unfortunately can't help you understand why.

  • 0

    I think it is because Python has stricter limitation on recursion depth. I've found many problems can't be solved by recursion in Python.

Log in to reply

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