判断二叉树中的两个结点是否为兄弟结点或者堂兄弟结点

兄弟: 深度相同, 双亲节点相同(同一个结点不能是兄弟)。
堂兄弟: 深度相同,双亲节点不同。

若询问的两个结点是兄弟,输出"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;
}

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值