输入样例1:
5
1 2 0
2 4 3
3 0 0
4 0 5
5 0 0
输出样例1:
3
4 5
输入样例2:
5
2 5 3
1 2 0
3 0 0
4 0 0
5 0 4
输出样例2:
3
4 5
左孩子存 儿子,右孩子存 兄弟
#include<bits/stdc++.h>
using namespace std;
struct tree{
int f,l,r;
tree()
{
f=-1;l=r=0;
}
}t[100001];
set<int> ans;
int m;
int gethead(int k)
{
if(t[k].f==-1) return k;
else return gethead(t[k].f);
}
void getans(int k,int h)
{
if(h>m)
{
m=h;
ans.clear();
ans.insert(k);
}
else if(h==m)
ans.insert(k);
if(t[k].l) getans(t[k].l,h+1);
if(t[k].r) getans(t[k].r,h);
}
int main()
{
int a,b,c,n;
cin>>n;
for(int i=0;i<n;i++)
{
scanf("%d%d%d",&a,&b,&c);
if(b)
{
t[a].l=b;
t[b].f=a;
}
if(c)
{
t[c].f=a;
t[a].r=c;
}
}
int r=gethead(1);
getans(r,1);
printf("%d\n",m);
for(set<int>::iterator it=ans.begin();it!=ans.end();it++)
{
if(it!=ans.begin()) printf(" ");
printf("%d",*it);
}
return 0;
}