兄弟: 深度相同, 双亲节点相同(同一个结点不能是兄弟)。
堂兄弟: 深度相同,双亲节点不同。
若询问的两个结点是兄弟,输出"brother" , 若询问的两个结点是堂兄弟,输出"cousin" ,否则输出"other relationship"
同一个结点的关系是“other relationship"
#include<stdio.h>
#include<stdlib.h>
typedef struct BiTNode
{
int data;
struct BiTNode* lchild, *rchild;
}BiTNode, *BiTree;
BiTree creat()
{
BiTree root = (BiTree)malloc(sizeof(BiTNode));
int x;
scanf("%d", &x);
if(x==-1)
root = NULL;
else
{
root->data = x;
root->lchild = creat();
root->rchild = creat();
}
return root;
}
int tag=0, f1=0, f2=0;
int d1=1, d2=1;
BiTree p1=NULL, p2=NULL, parent=NULL;
int x, y;
void relationship(BiTree bt, BiTree parent, int depth)
{
if(bt==NULL) return;
if(x==y){f1=1;f2=1;tag=1;}
if(bt->data == x){f1=1; p1=parent; d1=depth;}
if(bt->data == y){f2=1; p2=parent; d2=depth;}
if(f1&&f2)
{
if(tag) {printf("other relationship");exit(0);}
else if(d1==d2&&p1==p2)
{printf("brother");exit(0);}
else if(d1==d2&&p1!=p2)
{printf("cousin");exit(0);}
else
{printf("other relationship");exit(0);}
}
relationship(bt->lchild, bt, depth+1);
relationship(bt->rchild, bt, depth+1);
}
int main()
{
BiTree bt = creat();
scanf("%d%d", &x, &y);
relationship(bt, NULL, 1);
return 0;
}