We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Java Solution, using level order traversal using 2 queues
Start with putting 1 in the primary queue,
1. poll from primary queue, check if you need to swap the child i.e level % k == 0.
2. add the child indexes in secondary queuue.
repeat step 1 and 2 until primary queue is empty. once empty means level is done, go to next level.
poll all the indexes from secondary and add into primary.
do the inOrderTraversal of the tree and add the list to a list
public static List> swapNodes(List> indexes, List queries) {
// Write your code here
Queue primary = new LinkedList<>();
Queue secondary = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
for (int k : queries) {
primary.add(1);
int level = 1;
while (!primary.isEmpty()) {
while (!primary.isEmpty()) {
int p = primary.poll();
List<Integer> child = indexes.get(p - 1);
if (level % k == 0) { // swap left and right child
child.add(child.get(0));
child.remove(0);
}
child.stream().filter(ch -> ch != -1).forEach(secondary::add); //add the non null child to secondary queue representing next level
}
while (!secondary.isEmpty())
primary.add(secondary.poll());
level++;
}
List<Integer> traversal = new ArrayList<>();
inOrderTraversal(1, indexes, traversal);
res.add(traversal);
}
return res;
}
private static void inOrderTraversal(int root, List<List<Integer>> indexes, List<Integer> res) {
int left = indexes.get(root - 1).get(0);
if (left != -1)
inOrderTraversal(left, indexes, res);
res.add(root);
int right = indexes.get(root - 1).get(1);
if (right != -1)
inOrderTraversal(right, indexes, res);
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Swap Nodes [Algo]
You are viewing a single comment's thread. Return to all comments →
Java Solution, using level order traversal using 2 queues Start with putting 1 in the primary queue, 1. poll from primary queue, check if you need to swap the child i.e level % k == 0. 2. add the child indexes in secondary queuue. repeat step 1 and 2 until primary queue is empty. once empty means level is done, go to next level. poll all the indexes from secondary and add into primary. do the inOrderTraversal of the tree and add the list to a list
public static List> swapNodes(List> indexes, List queries) { // Write your code here Queue primary = new LinkedList<>(); Queue secondary = new LinkedList<>();