I/P:
12
10 20 -1 30 50 -1 60 -1 -1 40 -1 -1O/P: 2

For this we look at case 1 where a tree has only one element, in such a case height is 0 (in terms of edges). Therefore we will initialize our height variable with -1, so that when it does self work, one gets added to this making height of such a case 0.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Stack;
public class Height_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 height(Node node) {
// why height initiazed to -1 ??
// if I'm at root node, height should be 0
// but since, at the end we are incrementing height by 1
// Hence, height should be initialized to -1.
int height = -1;
for (Node child : node.children) {
height = Math.max(height, height(child));
}
height += 1;
return height;
}
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 h = height(root);
System.out.println(h);
// display(root);
}
}
No comments:
Post a Comment