CSES - Shared codeLink to this code:
https://cses.fi/paste/052f635c07bfa51c26f96a/
#include<bits/stdc++.h>
// #pragma GCC optimize("Ofast")
// #pragma GCC target("avx,avx2,fma")
// #pragma GCC optimization("unroll-loops")
// #pragma GCC optimize("unroll-loops")
// #pragma GCC optimize("fast-math")
// #pragma GCC optimize("no-stack-protector")
// #define ll __int128
#define ll long long
// #define ll int
#define f(i,a,b) for(int i=a;i<b;i++)
#define mod 1000000007
// #define mod 998244353
#define mp make_pair
#define uniq(v) (v).erase(unique(all(v)),(v).end())
#define ff first
#define ss second
#define rf(i,a,b) for(int i=a;i>=b;i--)
#define sc(a) scanf("%lld",&a)
#define pf printf
#define sz(a) (int)(a.size())
#define psf push_front
#define ppf pop_front
#define ppb pop_back
#define pb push_back
#define pq priority_queue
#define all(s) s.begin(),s.end()
#define sp(a) setprecision(a)
#define rz resize
#define ld long double
#define inf (ll)1e18
#define ub upper_bound
#define lb lower_bound
#define bs binary_search
#define eb emplace_back
const double pi = acos(-1);
ll binpow(ll a, ll b){ll res=1;while(b!=0){if(b&1)res*=a;a*=a;b>>=1;}return res;}
// ll binpow(ll a, ll b, ll md){ll res=1;a%=mod;while(b!=0){if(b&1)res*=a,res%=md;a*=a,a%=md;b>>=1;}return res%md;}
using namespace std;
int n;
vector<vector<int> > v;
vector<int> deg;
vector<bool> vis;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// freopen("xortransform.in","r",stdin);
// freopen("xortransform.out","w",stdout);
// #ifndef ONLINE_JUDGE
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
// #endif
int z=1;
// cin>>z;
f(i,1,z+1)
{
//cout<<"Case #"<<i<<": ";
int ans=0;
cin>>n;
v.rz(n+1),deg.rz(n+1),vis.rz(n+1);
f(i,0,n-1)
{
int l,r;
cin>>l>>r;
v[l].pb(r),v[r].pb(l);
deg[l]++,deg[r]++;
}
queue<int> q;
f(i,1,n+1)
{
if(deg[i]==1)
q.push(i);
}
while(!q.empty())
{
int nd=q.front();
q.pop();
vis[nd]=1;
f(i,0,sz(v[nd]))
{
int node=v[nd][i];
if(!vis[node])
{
ans++,vis[node]=1;
f(j,0,sz(v[node]))
{
int cur=v[node][j];
deg[cur]--;
if(!vis[cur] && deg[cur]==1)
q.push(cur);
}
}
}
}
cout<<ans<<"\n";
}
}