第一个,stoi可以实现string到int的转变
第二个,读入数字时,一定不能用char而必须用string,因为如果是两位数及以上,char只能读到一位!!
#include<bits/stdc++.h>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int n,now;
bool ischild[33];
struct node
{
int lchild=-1,rchild=-1;
}tree[25];
bool bfs(int root,std::vector<int> &k)
{
std::queue<int> q;
q.push(root);
int cnt=0;
while(!q.empty())
{
int now=q.front();
q.pop();
k[cnt++]=now;
if(now==-1&&cnt<=k.size()) return false;
else if(cnt==k.size()) return true;
q.push(tree[now].lchild);
q.push(tree[now].rchild);
}
}
void windows_cmd_support_utf8(void)
{
#ifdef WIN32
system("chcp 65001 & cls");
#endif
}
inline int read()
{
int w=1,x=0;
char ch=getchar();
while(ch>'9'||ch<'0')
{
if(ch=='-') w=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-48,ch=getchar();
return w*x;
}
signed main(void)
{
windows_cmd_support_utf8();
n=read();
std::vector<int> k(n);
string l,r;//有可能是两位数,不能只用char
for(int i=0;i<n;i++)
{
cin>>l>>r;//
if(l!="-")
{
tree[i].lchild=stoi(l);
ischild[stoi(l)]=true;
}
else tree[i].lchild=-1;
if(r!="-")
{
tree[i].rchild=stoi(r);
ischild[stoi(r)]=true;
}
else tree[i].rchild=-1;
}
int root=0;
for(int i=0;i<n;i++)
if(ischild[i]==false)
{
root=i;
}
if(bfs(root,k))
{
printf("YES %d",k[n-1]);
return 0;
}
else
{
printf("NO %d",root);
return 0;
}
}