Thursday, February 24, 2022

Level Order Traversal - Line Wise 1: Main Queue with count of children

I/P:

24

10 20 50 -1 60 -1 -1 30 70 -1 80 110 -1 120 -1 -1 90 -1 -1 40 100 -1 -1 -1

O/P:

10 

20 30 40 

50 60 70 80 90 100 

110 120 


Step 1. Calculate the size of queue

Step 2. Perform below action size time

    a. Remove the peek node from queue

    b. Print the data of node removed

    c. Add all the childs

Step 3. Println for next line



import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Queue;
import java.util.Stack;

public class LevelOrder_Linewise_Of_GenericTree {
private static class Node {
int data;
ArrayList<Node> children = new ArrayList<>();
}

public static void display(Node node) {
String str = node.data + " -> ";
for (Node child : node.children) {
str += child.data + ", ";
}
str += ".";
System.out.println(str);

for (Node child : node.children) {
display(child);
}
}

public static Node construct(int[] arr) {
Node root = null;

Stack<Node> st = new Stack<>();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == -1) {
st.pop();
} else {
Node t = new Node();
t.data = arr[i];

if (st.size() > 0) {
st.peek().children.add(t);
} else {
root = t;
}

st.push(t);
}
}

return root;
}

public static void levelOrderLinewise(Node node) {
Queue<Node> queue = new ArrayDeque<>();
queue.add(node);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
// remove
Node out = queue.remove();
// print
System.out.print(out.data + " ");
for (Node child : out.children)
queue.add(child);

}
System.out.println();
}
}

public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
String[] values = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(values[i]);
}

Node root = construct(arr);
levelOrderLinewise(root);
}

}




No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...