• + 0 comments
    from collections import deque
    sys.setrecursionlimit(500000)
    
    #
    # Complete the 'swapNodes' function below.
    #
    # The function is expected to return a 2D_INTEGER_ARRAY.
    # The function accepts following parameters:
    #  1. 2D_INTEGER_ARRAY indexes
    #  2. INTEGER_ARRAY queries
    #
    
    class node:
        def __init__(self, info, depth):
            self.info = info
            self.depth = depth
            self.left = None
            self.right = None
            
    def createTree(indexes):
        q = deque()
        root = node(1, 1)
        q.append(root)
        
        for x in indexes:
            ele = q.popleft()
            if x[0] != -1:
                ele.left = node(x[0], ele.depth + 1)
                q.append(ele.left)
            if x[1] != -1:
                ele.right = node(x[1], ele.depth + 1)
                q.append(ele.right)
            if len(q) == 0:
                break
                
        return root
        
        
    def inorder(root):
        values = []
        
        def inorder_traversal(root):
            if root is None:
                return
            inorder_traversal(root.left)
            values.append(root.info)
            inorder_traversal(root.right)
            
        inorder_traversal(root)
        return values
            
            
    def nodesStack(root):
        stack = [root]
        values = []
        while len(stack) != 0:
            ele = stack.pop()
            values.append(ele)
            if ele.left:
                stack.append(ele.left)
            if ele.right:
                stack.append(ele.right)
                
        return values
    
    def swapNodes(indexes, queries):
        # Write your code here
        root = createTree(indexes)
        nodes = nodesStack(root)
        finalarray = []
        for k in queries:
            for n in nodes:
                if n.depth % k == 0:
                    if n.left is None and n.right is None:
                        pass
                    elif n.left is None and n.right:
                        n.left = n.right
                        n.right = None
                    elif n.right is None and n.left:
                        n.right = n.left
                        n.left = None
                    else:
                        temp = n.right
                        n.right = n.left
                        n.left = temp
            finalarray.append(inorder(root))
            
        return finalarray