• + 0 comments

    Java:

    private static Node createTree(Node root, List<List<Integer>> indexes)
        {
            Queue<Node> queue = new ArrayDeque<>();
            queue.add(root);
            int i = 0;
            while(!queue.isEmpty() && (i < indexes.size()))
            {
                List<Integer> index = indexes.get(i++);
                Node n = queue.remove();
                if(index.get(0) > 1)
                {
                    n.left = new Node(index.get(0));
                    queue.add(n.left);
                }
                if(index.get(1) > 1)
                {
                    n.right = new Node(index.get(1));
                    queue.add(n.right);
                } 
            } 
            return root;
        } 
        
        private static void inOrder(Node root, List<Integer> indexes)
        {
            if(root == null)
                return;
            inOrder(root.left, indexes);
            indexes.add(root.data); 
            inOrder(root.right, indexes);
        }
        
        private static void swap(Node root, int level, int query)
        {
            if((root == null) || root.left == root.right)
                return;
            if((level % query) == 0)
            {
                Node a = root.left;
                root.left = root.right;
                root.right = a;
            }
            swap(root.left, level+1, query);
            swap(root.right, level+1, query);
        }
        
         public static List<List<Integer>> swapNodes(List<List<Integer>> indexes, List<Integer> queries) {
        // Write your code here
            List<List<Integer>> result = new ArrayList<>();
            Node root = new Node(1);
            createTree(root, indexes);
            for(Integer q : queries)
            {
                List<Integer> list = new ArrayList<>();
                swap(root, 1, q);
                inOrder(root, list);
                result.add(list);
            }
             
            return result;
        }