Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save KhaledElshamy/df6b3ef5de5734b50b2543649c2c0a3f to your computer and use it in GitHub Desktop.
Save KhaledElshamy/df6b3ef5de5734b50b2543649c2c0a3f to your computer and use it in GitHub Desktop.
Compute Tree Height-Data Structure-Coursera Course
#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;
}
@Ujjk29
Copy link

Ujjk29 commented Jul 11, 2018

I have gone through your solution, but I can't understand how they are making tree . I know -1 becomes the root, but what about other nodes? Please explain the question, I have read this on internet, but this whole question seems incomplete to me. How we put other nodes in tree except the root.

Thank You in advance.

@Ujjk29
Copy link

Ujjk29 commented Jul 11, 2018

Thanks I got the whole question and algo.

@annabechang
Copy link

annabechang commented Jan 2, 2019

@Ujjk29 is it possible that you can share what you learned? I am a little confused about how they complete the order of the nodes too. thanks

@quocthinhle
Copy link

thank you. im going to solve this problem by recursion and using struct too.

@rajatpandey441
Copy link

Very nicely written code.

@rishikumarprajapati
Copy link

Thanks I got the whole question and algo.

Can you share your knowledge?

@Timtim477
Copy link

Can you please explain the method you have applied to get the height of tree?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment