'Recursion tree for Heap's algorithm

I am trying to understand how the Heap's algorithm for permutations works but I find it very hard to understand. I haven't found an example of recursion tree to explain how the code works. Can anyone provide one for me?

Let's say I want to compute all permutations of the list [1,2,3,4] in python. I know how to implement the algorithm in python,

def heapPermutation(a, size):
    if size == 1:
        return
    for i in range(size):
        heapPermutation(a,size-1)
            
        if size % 2 == 0:
            a[i],a[size-1] = a[size-1],a[i]
        else:
            a[0],a[size-1] = a[size-1],a[0]

but still I get confused by the recursive calls.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source