I/P: { 10, 20, 40, -1, -1, 30, 50, -1, 60}
O/P:
10 -> 20, 30, .
20 -> 40, .
40 -> .
30 -> 50, 60, .
50 -> .
60 -> .

package pep.Day28;
import java.util.ArrayList;
import java.util.Stack;
public class Display_Generic_Tree {
private static class Node {
int data;
ArrayList<Node> children = new ArrayList<>();
}
public static void main(String[] args) {
int[] arr = new int[]{10, 20, 40, -1, -1, 30, 50, -1, 60};
Node root = null;
Stack<Node> stack = new Stack<>();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == -1)
stack.pop();
else {
Node child = new Node();
child.data = arr[i];
if (!stack.isEmpty()) {
stack.peek().children.add(child);
} else {
root = child;
}
stack.push(child);
}
}
System.out.println(root);
display(root);
}
// Expectation -> d(10): 10 will print itself and its family
// FAITH -> d(20), d(30): will print itself and its family
// d(10) = self(10) + d(20)+ d(30)
private static void display(Node root) {
// self(10)
String str = root.data + " -> ";
for (Node child : root.children) {
str += child.data + ", ";
}
str += ".";
System.out.println(str);
// d(20)+ d(30)
for (Node child : root.children) {
display(child);
}
}
}
No comments:
Post a Comment