复习了dfs的写法
用队列和循环,判断标准是队列是否有内容
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
int n;
int head[30];
struct node{
int left,right;
};
int main()
{
cin >> n;
memset(head,-1,sizeof(head));
vector<node> ans(n);
for(int i=0; i<n; i++){
string a,b;
cin >> a >> b;
if(a != "-"){
ans[i].left = stoi(a);
head[stoi(a)] = i;
}
else ans[i].left = -1;
if(b!= "-"){
ans[i].right = stoi(b);
head[stoi(b)] = i;
}
else ans[i].right = -1;
}
int root;
for(int i=0; i<n; i++){
if(head[i]==-1){
root = i;
break;
}
}
queue<int> q;
q.push(root);
int cnt=0,last;
while(!q.empty()){
int temp = q.front();
q.pop();
if(temp != -1){
cnt++;
last = temp;
}
else{
if(cnt!=n) cout << "NO " << root << endl;
else cout << "YES " << last << endl;
break;
}
q.push(ans[temp].left);
q.push(ans[temp].right);
}
return 0;
}