Thursday, February 24, 2022

Level-order Of Generic Tree / BREADTH FIRST TRAVERSAL

I/O: 

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 .



RPA: Remove, Print and Add to operate the queue. This rule says that, remove the element from the queue, print that element and then add its children to the queue.



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_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 int size(Node node) {
int s = 0;

for (Node child : node.children) {
s += size(child);
}
s += 1;

return s;
}

public static void levelOrder(Node node) {
// add parent node
Queue<Node> queue = new ArrayDeque<>();
queue.add(node);
while (!queue.isEmpty()) {
// remove
Node out = queue.remove();

// print
System.out.print(out.data + " ");

// add child
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);
levelOrder(root);
}

}


Time Complexity:

O(n) We travel to all the elements of the tree. Every node is processed individually in a while loop.

Space Complexity:

O(n) A queue of size n will be used.


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:...