Created
May 13, 2017 13:50
-
-
Save KhaledElshamy/df6b3ef5de5734b50b2543649c2c0a3f to your computer and use it in GitHub Desktop.
Compute Tree Height-Data Structure-Coursera Course
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
int root=0; | |
int main() | |
{ | |
int n; | |
cin>>n; | |
vector< vector<int> >nodes(n); | |
queue<int>q; | |
int a[n]; | |
for(int i=0;i<n;i++) | |
{ | |
cin>>a[i]; | |
if(a[i]==-1)root=i; | |
else { | |
nodes[a[i]].push_back(i); | |
} | |
} | |
q.push(root); | |
int height=0; | |
while(true) | |
{ | |
int nodecount=q.size(); | |
if(nodecount==0){ | |
cout<<height<<endl; | |
return 0; | |
} | |
height+=1; | |
while(nodecount>0){ | |
int node=q.front(); | |
q.pop(); | |
if(!nodes[node].empty()){ | |
for(int i=0;i<nodes[node].size();i++) | |
q.push(nodes[node][i]); | |
} | |
nodecount--; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you please explain the method you have applied to get the height of tree?