CSES - Shared codeLink to this code: https://cses.fi/paste/53eff2f0f436fb2861505d/
#include<bits/stdc++.h>
using namespace std;

typedef long long int ll;
#define IOS ios_base::sync_with_stdio(0);  cin.tie(0); cout.tie(0);

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>order_set;
typedef pair<int, int>pr;
#define all(i)     i.begin() , i.end()
#define ft     first
#define sn     second
#define pb push_back

#define totalone(mask) __builtin_popcount(mask)
#define chkbit(mask,bit) (mask&(1LL << bit))
#define setbit(mask,bit) (mask|(1LL << bit))
#define cngbit(mask,bit) (mask^(1LL << bit))

#define en "\n"
#define dbg(x) cerr<<#x<<" is : "<<x<<en;
#define yes cout<<"YES\n"
#define no cout<<"NO\n"
#define report cout<<-1<<en
#define sum(n) ((1LL*(n)*(n+1))/ 2LL)
#define sqr(n) (1LL*(n)*(n))
#define vag(a,b) ((a + b - 1)/b)
#define coutv(v) for(auto i: v) cout<<i<<" ";cout<<en;
#define cinv(v) for(auto &i: v) cin >> i;

const int MAXN = 200005;
#define inf 1e15
const int mod = 1e9 + 7;

ll n;
vector<ll>g[MAXN];
ll vis[MAXN];
ll ans[MAXN];
ll siz[MAXN];
ll niche[MAXN];

void dfs(ll nd)
{
    vis[nd] = 1;
    siz[nd] = 1;

    for (auto i : g[nd])
    {
        if (vis[i]) continue;
        dfs(i);
        siz[nd] += siz[i];
    }
}

void dfs2(ll nd)
{
    vis[nd] = 1;
    for (auto i : g[nd])
    {
        if (vis[i]) continue;
        dfs2(i);

        niche[nd] += (niche[i] + siz[i]);
    }
}

void dfs3(ll nd)
{
    vis[nd] = 1;
    for (auto i : g[nd])
    {
        if (vis[i]) continue;
        ll an1 = ans[nd] - niche[i] - (siz[i]);
        ll an2 = n - siz[i];
        ans[i] = an1 + an2 + niche[i];
        dfs3(i);
    }
}

void solve()
{
    cin >> n;
    for (ll i = 1; i < n; i++)
    {
        ll x, y;
        cin >> x >> y;
        g[x].pb(y);
        g[y].pb(x);
    }

    dfs(1);
    // for (ll i = 1; i <= n; i++) cout << siz[i] << " "; cout << en;

    memset(vis, 0, sizeof(vis));

    dfs2(1);
    memset(vis, 0, sizeof(vis));

    ans[1] = niche[1];

    dfs3(1);

    for (ll i = 1; i <= n; i++) cout << ans[i] << " "; cout << en;


}
int main()
{
    IOS;
    ll t;
    t = 1;
    // cin >> t;

    int c = 0;
    while ( t-- )
    {
        // cout<<"Case "<<++c<<": ";
        solve();
    }
    return 0;
}