Thinking:
Find the shift of status. And observe the nature of rotation.
Use father's status to solve both sons' status.
AC code:
#include<iostream>
#include<cstring>
using namespace std;
int root;
int L[100005];// L[i] -> i's left son
int R[100005];
int dp[100005];
int h[100005];// how deep can this node stretch
bool f[100005];// f[i] -> does this node have a parent?
inline int find_height(int r)
{
if (r == 0)// reach the end
{
return 0;
}
h[r] =max(find_height(L[r]),find_height(R[r])) + 1;
return h[r];
}
inline void dfs(int x, int lh,int rh,int lcount,int rcount)
{
if (x == 0)// reach the end
return;
if (!f[x])// if x is root
{
dp[x] = 1 + max(h[L[x]], h[R[x]]);
}
else{
dp[x] = max(max(lh, rh), max(h[L[x]] + lcount, h[R[x]] + rcount)) + 1;
}
dfs(L[x], lh, max(rh, h[R[x]] + rcount + 1), lcount, rcount + 1);
dfs(R[x], max(lh,h[L[x]]+lcount+1),rh,lcount+1, rcount );
}
int main()
{
int n;
while (scanf("%d", &n) && n)
{
for (int i = 1; i <= n; i++)
{
f[i] = 0;
}
for (int i = 1; i <= n; i++)
{
int left_child, right_child;
scanf("%d%d", &left_child, &right_child);
L[i] = left_child;
R[i] = right_child;
f[left_child] = 1;
f[right_child]=1;
}
for (int i = 1; i <= n; i++)
if (f[i]==false)
{
root = i;// find the root
break;
}
find_height(root);// search from the root
dfs(root, 0, 0, 0, 0);
for (int i = 1; i <= n; i++)
printf("%d\n", dp[i]);
}
return 0;
}