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, . 20 -> 50, 60, . 50 -> . 60 -> . 30 -> 70, 80, 90, . 70 -> . 80 -> 110, 120, . 110 -> . 120 -> . 90 -> . 40 -> 100, . 100 -> .
10 -> 40, 30, 20, . 40 -> 100, . 100 -> . 30 -> 90, 80, 70, . 90 -> . 80 -> 120, 110, . 120 -> . 110 -> . 70 -> . 20 -> 60, 50, . 60 -> . 50 -> .

package pep.Day29;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Stack;
public class Mirror_A_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 mirror(Node node) {
// faith: each children will bring the reverse child of their own
for (Node child : node.children)
mirror(child);
// expectation meet faith: reverse the childern arraylist
Collections.reverse(node.children);
}
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);
display(root);
mirror(root);
display(root);
}
}
Time Complexity: O(n) The time complexity for the function is linear as we post traversing the tree.
Space Complexity: O(nlogn) The space complexity for the function is equal to the height of the tree due to the recursion stack.
No comments:
Post a Comment