https://www.acwing.com/problem/content/description/4274/
#include<bits/stdc++.h>
#include<string.h>
using namespace std;
const int N = 1010;
int post[N], in[N], pos[N];
int l[N], r[N], f[N];
int depth[N];
int n, m;
int build(int pl, int pr, int il, int ir)
{
int root = post[pr];
int k = pos[root];
if (k > il)
{
int t = build(pl, pr - 1 - (ir - k - 1) - 1, il, k - 1);
l[root] =t;
f[t] = root;
}
if (k < ir)
{
int t = build(pr - 1 - (ir - k - 1), pr - 1, k + 1, ir);
r[root] = t;
f[t] = root;
}
return root;
}
void dfs(int root,int u)
{
if (root == 0) return;
depth[root] = u;
if(l[root])dfs(l[root], u + 1);
if(r[root])dfs(r[root], u + 1);
}
bool check(int root)
{
if (root == 0) return true;
if ((l[root] != 0 && r[root] != 0) || ((l[root] == 0 && r[root] == 0)))
{
return check(l[root]) && check(r[root]);;
}
else
{
return false;
}
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++) cin >> post[i];
for (int i = 1; i <= n; i++) cin >> in[i], pos[in[i]] = i;
int root = build(1, n, 1, n);
dfs(root,1);
//cout<<root<<endl;
//cout << r[2] << endl;
cin >> m;
getchar();
string s;
for (int i = 1; i <= m; i++)
{
getline(cin,s);
if (s.find("root")!=-1)
{
stringstream ssin(s);
vector<int> temp(2);
sscanf(s.c_str(), "%d", &temp[0]);
cout << (temp[0]== root ? "Yes" : "No") << endl;
}
if (s.find("siblings") != -1)
{
stringstream ssin(s);
vector<int> temp(2);
sscanf(s.c_str(), "%d and %d", &temp[0], &temp[1]);
if (temp[0] != temp[1]) cout << (f[temp[0]]==f[temp[1]] ? "Yes" : "No") << endl;
else cout << "No" << endl;
}
if (s.find("parent") != -1)
{
vector<int> temp(2);
stringstream ssin(s);
sscanf(s.c_str(), "%d is the parent of %d", &temp[0], &temp[1]);
cout << (temp[0] == f[temp[1]] ? "Yes" : "No") << endl;
}
if (s.find("left") != -1)
{
vector<int> temp(2);
stringstream ssin(s);
sscanf(s.c_str(), "%d is the left child of %d", &temp[0], &temp[1]);
cout << (temp[0] == l[temp[1]] ? "Yes" : "No") << endl;
}
if (s.find("right") != -1)
{
vector<int> temp(2);
stringstream ssin(s);
sscanf(s.c_str(), "%d is the right child of %d", &temp[0], &temp[1]);
cout << (temp[0] == r[temp[1]] ? "Yes" : "No") << endl;
}
if (s.find("level") != -1)
{
vector<int> temp(2);
stringstream ssin(s);
sscanf(s.c_str(), "%d and %d", &temp[0], &temp[1]);
cout << (depth[temp[0]] == depth[temp[1]] ? "Yes" : "No") << endl;
}
if (s.find("full") != -1)
{
cout << (check(root) == true ? "Yes" : "No") << endl;
}
}
return 0;
}
标签:sscanf,cout,temp,int,二叉树,str,root,结构
From: https://www.cnblogs.com/xjtfate/p/16622528.html