#include<cstdio>
#include<vector>
using namespace std;
const int N=1e5+100;
int n,dep[N],g[N][21];
int dc[N],tc[N],exde,ans;
short out[N];
vector<int>e[N];
void dfs(int x,int de){
exde=max(exde,de);
for(int i=0;i<e[x].size();i++){
if(!dep[e[x][i]]){
dep[e[x][i]]=dep[x]+1;
g[e[x][i]][0]=x;
dfs(e[x][i],de+1);
}
}
}
int lca(int a,int b){
if(dep[a]<dep[b]) swap(a,b);
int t=dep[a]-dep[b];
int ans=0x7fffffff;
for(int i=0;i<=20;i++){
if((1<<i)&t){
a=g[a][i];
}
}
if(a==b) return a;
for(int i=20;i>=0;i--){
if(g[a][i]!=g[b][i]){
a=g[a][i];
b=g[b][i];
}
}
return min(g[a][0],g[b][0]);
}
int main(){
scanf("%d",&n);
if(n==1){printf("1
");return 0;}
for(int i=1,x,y;i<=n;i++){
scanf("%d%d",&x,&y);
if(x) e[i].push_back(x),out[i]++;
if(y) e[i].push_back(y),out[i]++;
}
for(int i=1;i<=n+1;i++) if(!out[i]) dc[++dc[0]]=i;
dfs(1,0);
for(int j=1;j<=20;j++){
for(int i=1;i<=n;i++){
g[i][j]=g[g[i][j-1]][j-1];
}
}
int tx=0;
for(int i=1;i<=dc[0];i++) if(dep[dc[i]]==exde) {tx=dc[i];break;}
for(int i=1;i<tx;i++){
int zj=lca(dc[i],tx);
ans=max(ans,dep[dc[i]]-dep[zj]+dep[tx]-dep[zj]);
}
for(int i=tx+1;i<=dc[0];i++){
int zj=lca(dc[i],tx);
ans=max(ans,dep[dc[i]]-dep[zj]+dep[tx]-dep[zj]);
}
printf("%d
",ans);
return 0;
}
//朴素搜索:一遍dfs求出某个节点到到叶子节点的最长距离,记为len[i],在求出以某个点为祖先的最长链长度,记为f[i],取最大的f[i]即为答案
#include<cstdio>
#include<iostream>
#define M 100010
using namespace std;
int lch[M],rch[M],len[M],f[M],n;
inline const int read(){
register int x=0,f=1;
register char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
void dfs(int x){
if(len[x])return;
if(lch[x])dfs(lch[x]);
if(rch[x])dfs(rch[x]);
if(rch[x]||lch[x])len[x]=max(len[lch[x]],len[rch[x]])+1;
}
int main(){
n=read();
for(int i=1;i<=n;i++)lch[i]=read(),rch[i]=read();
dfs(1);
for(int i=1;i<=n;i++){
f[i]=len[lch[i]]+len[rch[i]];
if(lch[i])f[i]++;
if(rch[i])f[i]++;
}
int ans=0;
for(int i=1;i<=n;i++) ans=max(ans,f[i]);
printf("%d",ans);
return 0;
}
//树形dp写的
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define N 100001
int n,l[N],r[N],ans;
int dfs(int k){
if (k==0) return 0;
int x=dfs(l[k]),y=dfs(r[k]);
ans=max(ans,x+y);
return max(x,y)+1;
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d%d",&l[i],&r[i]);
ans=max(ans,dfs(1)-1);
printf("%d",ans);
return 0;
}