• + 0 comments

    No need to build a tree. Just swap the numbers in the list.

    sys.setrecursionlimit(2000) 
    def swapNodes(indexes, queries):
        # Write your code here
        result = []
        indexes = [[]]+indexes
        for k in queries:
            res = []
            swap(indexes, 0, 1, k, res)
            result.append(res)
        return result
    
    def swap(nodes, depth, curr, k, result):
        if curr == -1: 
            return
        if depth % k == k - 1:
            nodes[curr][0], nodes[curr][1] = nodes[curr][1], nodes[curr][0]
        swap(nodes, depth + 1, nodes[curr][0], k, result)
        result.append(curr)
        swap(nodes, depth + 1, nodes[curr][1], k, result)