题目 题意: 给定n个互不相同的整数(可能为负数,题目处处有坑),要求按照输入顺序插入一棵初始为空的二叉搜索树。之后有6种判断,分别是判断根、siblings、左儿子、右儿子、是否同层的关系。 思路: 可以真的建一颗树,但是也可以只用map维护相关信息进行建树,参考了一战南大大佬的code,tql. 时间复杂度: O(nlogn + mnlogn) = O(能过) 代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define OldTomato ios::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr)
#define fir(i,a,b) for(int i=a;i>s;
if(s == "root")
{
if(x == root) flag = true;
}
else
{
if(s == "parent")
{
cin>>s>>y;
if(l[x] == y || r[x] == y) flag = true;
}
else
{
if(s == "left")
{
cin>>s>>s>>y;
if(l[y] == x) flag = true;
}
else
{
cin>>s>>s>>y;
if(r[y] == x) flag = true;
}
}
}
}
void solve2(int &x,int &y,string &s)
{
cin>>y>>s>>s;
if(s == "siblings")
{
if(x > y) swap(x,y);
for(int i=0;i>s>>s>>s;
if(mp[x] && mp[x] == mp[y]) flag = true;
}
}
void solve()
{
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
cin>>n;
for(int i=0;i>a[i],l[a[i]] = r[a[i]] = INF; root = a[0]; mp[root] = 1;
for(int i=1;i>m;
while(m--)
{
int x,y;string s;
cin>>x>>s;
flag = false;
if(s == "is") solve1(x,y,s);
else solve2(x,y,s);
if(flag) cout
关注
打赏