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();
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