题目描述
PIPI最近在看家里的族谱,发现族谱刚好组成了一棵二叉树,现在PIPI想询问族谱中的两个结点是否为兄弟或者堂兄弟。
兄弟: 深度相同, 双亲节点相同(同一个结点不能是兄弟)。
堂兄弟: 深度相同,双亲节点不同。
输入
第一行按照先序输入族谱代表的二叉树,其中空节点用 -1 表示。
第二行输入两个数字 x y,代表询问的两个结点的值。
输出
若询问的两个结点是兄弟,输出"brother" , 若询问的两个结点是堂兄弟,输出"cousin" ,否则输出"other relathionship"
(relationship写错了 , 请同学们直接复制"other relathionship")
样例输入
1 2 -1 4 -1 -1 3 -1 5 -1 -1 4 5
样例输出
cousin
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct BiNode{
int data;
struct BiNode *lchild;
struct BiNode *rchild;
}*BiTree;
//创建一棵二叉树
void CreateTree(BiTree &T){
int data;
scanf("%d",&data);
if(cin.get()!='\n'){
if(data==-1){
T=NULL;
}else{
T=(BiTree)malloc(sizeof(BiNode));
T->data=data;
CreateTree(T->lchild);
CreateTree(T->rchild);
}
}
}
//获取x父结点所在层次和父结点的值
void Findnode(char x, BiTree T,BiTree father,BiTree &father_need,int height,int &height_need){
if (T != NULL){
if (T->data == x){
height_need=height;
father_need = father;
return;
}else{
father = T;
}
Findnode(x, T->lchild, father, father_need,height + 1,height_need);
Findnode(x, T->rchild, father, father_need,height + 1,height_need);
}
}
int main(void){
BiTree T;
CreateTree(T);
int A,B;
scanf("%d%d",&A,&B);
if(A==B){
printf("other relathionship\n");
}else{
BiTree fatherA = NULL,fatherB = NULL;//重点在于先将父节点置空
BiTree neededA = NULL,neededB = NULL;//将待查节点置空
int heightA = 0,heightB = 0;//高度初始化为0
Findnode(A, T, neededA, fatherA, 1, heightA);//使用查找函数
Findnode(B, T, neededB, fatherB, 1, heightB);
if(heightA==heightB){//深度相同
if(fatherA->data==fatherB->data){//A与B父结点相同
printf("brother\n");
}else{//深度不同
printf("cousin\n");
}
}else{
printf("other relathionship\n");
}
}
return 0;
}