Code:
//二叉排序树的创建,插入,判断操作以及其简单应用
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#define OK 1
#define ERROR 0
using namespace std;
//二叉排序树的存储结构定义
typedef int ElementType;
typedef int Status;
typedef struct TNode *Position;
typedef Position BSTree;
struct TNode{
ElementType Data;
BSTree lchild;
BSTree rchild;
};
Status InsBST(BSTree T, ElementType e, BSTree &f) //判断是不是已经存在
//并且将需要插入位置的父节点通过引用带回,后续操作可以直接插入
{
TNode *p = T;
f = NULL;
while(p != NULL && e != p->Data)
{
if(e > p->Data){
f=p; p=p->rchild;
}
else{
f=p; p=p->lchild;
}
}
if(!p)return OK;
else return ERROR;
}
Status CreateBST(BSTree &T)
{
T=NULL;
int N;
scanf("%d", &N); //节点的个数
if(N == 0) //空树
return OK;
else
{
int e;
scanf("%d", &e); N--; //根节点
T = (TNode*) malloc(sizeof(TNode)), T->Data = e, T ->lchild = NULL, T->rchild = NULL;
}
while(N--)
{
int e;
scanf("%d", &e);
TNode *f;
if(InsBST(T,e, f) != ERROR) //没找到,可以插入
{
TNode *p;
p = (TNode*) malloc (sizeof(TNode));
p->Data = e, p->lchild = NULL, p->rchild = NULL;
if(f->Data > e)
f->lchild = p;
else
f->rchild = p;
}
}
}
bool IsRoot(BSTree T, int e)
{
if(T->Data == e)
return true;
else
return false;
}
int IsFather(BSTree T, int a, int b)
{
while(T != NULL)
{
if(T->Data == a)
break;
if(T->Data > a)
T = T->lchild;
else
T = T->rchild;
}
if(T == NULL)
return 0;
bool flag1 = false, flag2 = false;
if(T->lchild != NULL)
{
if((T->lchild)->Data == b)
return 1;
}
if(T->rchild != NULL)
{
if((T->rchild)->Data == b)
return 2;
}
return 0;
}
void FindFather(BSTree T, int a, BSTree &f)
{
TNode *p = T;
f = NULL;
while(p != NULL && a != p->Data)
{
if(a > p->Data){
f=p; p=p->rchild;
}
else{
f=p; p=p->lchild;
}
}
if(p == NULL)
f = NULL;
return ;
}
int Rank(BSTree T, int a)
{
int ans = 1;
while(T != NULL && T->Data != a)
{
ans++;
if(T->Data > a)
T = T->lchild;
else
T = T->rchild;
}
if(T == NULL)
return -1;
return ans;
}
int main()
{
BSTree T;
CreateBST(T); //用引用实现树的创建
int N;
scanf("%d", &N);
while(N--)
{
int a, b;
string str, str1, str2;
cin >> a >> str;
if(str[0] == 'i')
{
cin >> str1 >> str2;
if(str2 == "root") {
if(IsRoot(T, a)) cout << "Yes" << endl;
else cout << "No" << endl;
}
else if(str2 == "right"){
cin >> str1 >> str2 >> b;
if(IsFather(T, b, a) == 2) cout << "Yes" << endl;
else cout << "No" << endl;
}
else if(str2 == "left"){
cin >> str1 >> str2 >> b;
if(IsFather(T, b, a) == 1) cout << "Yes" << endl;
else cout << "No" << endl;
}
else if(str2 == "parent"){
cin >> str2 >> b;
if(IsFather(T, a, b) != 0) cout << "Yes" << endl;
else cout << "No" << endl;
}
}
else
{
cin >> b >> str1 >> str2;
if(str2 == "siblings"){
BSTree t1, t2;
FindFather(T, a, t1); FindFather(T, b, t2);
if(t1 == NULL || t2 == NULL) cout << "No" << endl;
else if(t1->Data == t2->Data) cout << "Yes" << endl;
else cout << "No" << endl;
}
else {
cin >> str >> str1 >> str2;
int r1 = Rank(T, a), r2 = Rank(T, b);
if(r1 != -1 && r2 != -1 && r1 == r2) cout << "Yes" << endl;
else cout << "No" << endl;
}
}
}
return 0;
}