forked from golumall/Graph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeight_of_Generic_Tree.java
More file actions
72 lines (66 loc) · 1.22 KB
/
Copy pathHeight_of_Generic_Tree.java
File metadata and controls
72 lines (66 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.Scanner;
import java.util.Queue;
import java.util.LinkedList;
class Height_Ternary_Tree
{
int v,root;
LinkedList<Integer> adj[];
Height_Ternary_Tree(int v)
{
this.v=v;
adj=new LinkedList[v];
for(int i=0;i<v;i++)
{
adj[i]=new LinkedList<>();
}
}
void addEdge(int src,int dest)
{
adj[src].add(dest);
adj[dest].add(src);
}
int height()
{
boolean []visited=new boolean[v];
Queue<Integer> q=new LinkedList<>();
q.add(root);
visited[root]=true;
int k=0;
while(!q.isEmpty())
{
Queue<Integer> temp=new LinkedList<>();
while(!q.isEmpty())
{
int u=q.poll();
for(Integer i:adj[u])
{
if(!visited[i])
{
temp.add(i);
visited[i]=true;
}
}
}
q=temp;
k++;
}
return (k-1);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int []a=new int[n];
Height_Ternary_Tree graph=new Height_Ternary_Tree(n);
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
if(a[i]==-1)
{
graph.root=i;
continue;
}
graph.addEdge(a[i],i);
}
System.out.println(graph.height());
}
}