团体程序设计天梯赛 L3-016 二叉搜索树的结构 (30分)
题目链接:
L3-016 二叉搜索树的结构 (30分)
思路:
用map来映射某个点的左孩子和右孩子,同时记录层次;
然后依据输入进来的字符串挨个判断即可;
代码:
#include<bits/stdc++.h>
using namespace std;
const int INF = 1 << 30;
int n, m, a[123];
map<int, int> lf, rt, lv;
inline void push(int & x, int & u, int lvl) {
if(u == INF) { u = x; lv[x] = lvl; return; }
if(x < u) push(x, lf[u], lvl + 1);
else push(x, rt[u], lvl + 1);
}
inline void out(bool flag) { puts(flag ? "Yes" : "No"); }
inline void solve1(int & x, int & y, string & s) {
cin >> s >> s;
if(s == "root") { out(a[0] == x); return; }
if(s[0] == 'p') { cin >> s >> y; out(y == lf[x] || y == rt[x]); return; }
if(s[0] == 'l') { cin >> s >> s >> y; out(lf[y] == x); return; }
if(s[0] == 'r') { cin >> s >> s >> y; out(rt[y] == x); }
}
inline void solve2(int & x, int & y, string & s) {
cin >> y >> s >> s;
if(s[0] == 's') {
if(x > y) swap(x, y);
for(int i = 0; i < n; i++) if(lf[a[i]] == x && rt[a[i]] == y) {
out(true); return;
}
out(false);
}else out(lv[x] == lv[y] && lv[x]), getline(cin, s);
}
int main() {
#ifdef MyTest
freopen("Sakura.txt", "r", stdin);
#endif
cin >> n;
for(int i = 0; i < n; i++) {
cin >> a[i];
lf[a[i]] = rt[a[i]] = INF;
}
for(int i = 1; i < n; i++) push(a[i], a[0], 1);
for(cin >> m; m--;) {
int x, y;
string s;
cin >> x >> s;
if(s[0] == 'i') solve1(x, y, s);
else solve2(x, y, s);
}
return 0;
}