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, .
20 -> 50, .
50 -> 60, .
60 -> 30, .
30 -> 70, .
70 -> 80, .
80 -> 110, .
110 -> 120, .
120 -> 90, .
90 -> 40, .
40 -> 100, .
100 -> .
FAITH: Linearize method, linear bhi krega and tail bhi laakr dega
package pep.Day29;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Stack;
public class Linearize_A_GenericTree_EfficientWay {
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 Node linearize(Node node) {
// woh khud ek leaf node hai, islea vhi return kr do
// node.children.size() = 0 ho gya to, node.children.size() - 1 = -ve aaega
if (node.children.size() == 0)
return node;
Node lastNode = node.children.get(node.children.size() - 1);
// last ki tail mil gae, also, last linearize bhi ho gya
Node lastNode_Tail = linearize(lastNode);
while (node.children.size() > 1) {
Node last = node.children.remove(node.children.size() - 1);
Node secondLast = node.children.get(node.children.size() - 1);
// second last ki tail mil gae, also, linearize bhi ho gya
Node secondLastNode_Tail = linearize(secondLast);
secondLastNode_Tail.children.add(last);
}
return lastNode_Tail;
}
private static Node getTail(Node node) {
while (!node.children.isEmpty())
node = node.children.get(0);
return node;
}
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);
linearize(root);
display(root);
}
}
No comments:
Post a Comment