2
$\begingroup$

As I have read in this answer: What is tail recursion? tail recursion is a special case of recursion where the calling function does no more computation after making a recursive call.

Here after the recursive call we just assign the result to another variable. Can we consider this code as tail recursion?

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:

        if not head or not head.next:
            return head

        head_ = head
        head_next = head.next
        head_next_next = head.next.next

        head_next.next = head_

        head_.next = self.swapPairs(head_next_next)

        return head_next
$\endgroup$

1 Answer 1

2
$\begingroup$

It is considered tail recursion if there is no computation between the recursive call and the return.

In your example there is no computation, only an assignment.

It would depend on the actual compiler if code for an optimised tail recursive call was made at this point, but yes some compilers could treat this as a tail recursive call.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.