#include 3
<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ld long double
#define N (1<<18)
#define M 1000000007
#define P complex<long long>
#define X real()
#define Y imag()
using namespace std;
int n, a, b, par[401010], lvl[401010], cnt=2, rs[401010], l[402020], r[402020], ans;
vector<int> laps[401010], v, v2; // laps
vector<int> taso[402020];
void haku(int s) {
if(l[s]) {
lvl[l[s]] = lvl[s]+1;
haku(l[s]);
}
if(r[s]) {
lvl[r[s]] = lvl[s]+1;
haku(r[s]);
}
v.push_back(s);
taso[lvl[s]].push_back(s);
}
void haku2(int s) {
bool ok = false;
if(l[s]) {
haku2(l[s]);
} else {
v2.push_back(lvl[s]);
ok = true;
}
if(r[s]) {
haku2(r[s]);
} else {
}
}
int main() {
cin.tie(0);
cout.tie(0);
ios_base::sync_with_stdio(0);
cin >> n;
rs[1] = 1;
for(int i=1; i<=n; i++) {
cin >> a >> b;
int aS = cnt;
if(a != -1)
rs[a] = aS;
cnt++;
int bS = cnt;
if(b != -1)
rs[b] = bS;
cnt++;
l[rs[i]] = aS;
r[rs[i]] = bS;
laps[rs[i]].push_back(aS);
laps[rs[i]].push_back(bS);
}
haku(1);
for(int i=200020; i>=0; i--) {
for(auto u:taso[i]) {
if(l[u]) {
lvl[u] = max(lvl[u], lvl[l[u]]);
}
if(r[u]) {
lvl[u] = max(lvl[u], lvl[r[u]]);
}
}
}
for(int i=200020; i>=0; i--) {
for(auto u:taso[i]) {
if(l[u]) {
lvl[u] = min(lvl[u], lvl[l[u]]);
}
if(r[u]) {
lvl[u] = min(lvl[u], lvl[r[u]]);
}
if(l[u] && r[u]) {
if(lvl[l[u]] < lvl[r[u]]) {
ans++;
swap(r[u], l[u]);
}
}
}
}
haku2(1);
bool ok = false;
int ed = v2[0];
for(auto u:v2) {
if(u != ed) {
if(ed-u != 1) {
cout << -1;
exit(0);
} else {
if(ok) {
cout << -1;
exit(0);
} else {
ok = true;
}
}
}
ed = u;
}
cout << ans << endl;
}