#include<iostream> #include<string> #include<map> #include<vector> #include<algorithm> #include<queue> #include<set> #include<stack> using namespace std; struct node { int left=-1, right=-1; int val; }; int num; int cnt[10001]; node arr[21]; int c = 0; int last; bool f; void bfs(int root) { queue<int> q; q.push(root); while (!q.empty()) { int temp = q.front(); if (temp == -1) { //cout << c; if (c == num) { f = 1; } else f = 0; break; } q.pop(); c++; q.push(arr[temp].left); q.push(arr[temp].right); last = temp; } } int main() { cin >> num; for (int i = 0; i < num; i++) { arr[i].val = i; string l, r; cin >> l >> r; if (l != "-") { arr[i].left = stoi(l); cnt[stoi(l)] = 1; } if (r != "-") { arr[i].right = stoi(r); cnt[stoi(r)] = 1; } } int root = 0; while (cnt[root] == 1) { root++; } bfs(root); //cout << f; if (f == 1) { cout << "YES" << ' ' << last; } else { cout << "NO" << ' ' << root; } system("pause"); }
一开始没考虑到有可能会大于10的数字,用了char,导致一直过不了三个点。。。