I/P:
12
10 20 -1 30 50 -1 60 -1 -1 40 -1 -1
O/P: 6
Expectation:
We will have an expectation that sizeOfTree(10) will return as the size of the tree rooted at 10.
Faith:
We already have faith that sizeOfTree(20), sizeOfTree(30), sizeOfTree(40) will return us the size of the respective trees. Now to establish the expectation from the faith what we have to do is:
sizeOfTree(root) = sum of sizeOfTree(child) + 1
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Stack;
public class Size_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) {
// write your code here
if (node == null) return 0;
int size = 0;
// Expectation: children apna size khud calculate kr lenge
// let 20,30,40 apni apni node ka count le aate hain
ArrayList<Node> children = node.children;
for (Node child : children)
size += size(child);
// end me 10 (parent) apna count +1 kr dega
return size + 1;
}
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);
int sz = size(root);
System.out.println(sz);
// display(root);
}
}
No comments:
Post a Comment