-
Notifications
You must be signed in to change notification settings - Fork 30
/
Height Using Parent Array.cpp
69 lines (52 loc) · 1.53 KB
/
Height Using Parent Array.cpp
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
/*
Solution by Rahul Surana
***********************************************************
Given a parent array arr[] of a binary tree of N nodes.
Element at index i in the array arr[] represents the parent of ith node, i.e, arr[i] = parent(i).
Find the height of this binary tree.
Note: There will be a node in the array arr[], where arr[i] = -1, which means this node is the root of binary tree.
***********************************************************
*/
// { Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution{
public:
int findHeight(int N, int arr[]){
vector<int> h(N,1);
int ans = 1;
for(int i = 0; i<N;i++){
if(h[i] != 1) ans = max(h[i],ans);
else{
int x = i;
// int c = 0;
while(arr[x]!=-1){
h[x] = h[arr[x]]+1;
x = arr[x];
// cout << x<<" ";
}
ans = max(h[i],ans);
}
// cout << "\n";
}
return ans;
}
};
// { Driver Code Starts.
int main(){
int t;
cin>>t;
while(t--){
int N;
cin>>N;
int arr[N];
for(int i = 0;i < N;i++)
cin>>arr[i];
Solution ob;
cout<<ob.findHeight(N, arr)<<"\n";
}
return 0;
} // } Driver Code Ends