子孙关系判断

已知二叉树的先序序列,判断结点u是否是结点v的子孙,是就输出v到u的路径长度,否则输出NO。假设结点个数少于50个。

输入格式:
输入共二行,第一行中给出先序序列,第二行给出两个顶点。*表示空树。

输出格式:
输出一个整数或NO。

输入样例1:
ABCDE*GF***
BE
输出样例1:
2
输入样例2:
ABCDE*GF***
CE
输出样例2:
NO

#include<stdio.h>
#include<stdlib.h>

typedef char TElemType;
typedef int Status;

#define OK 1
#define ERROR 0
#define OVERFLOW -1

typedef struct BiNode
{
    TElemType data;
    struct BiNode *lchild,*rchild;
} BiNode,*BiTree;
typedef struct
{
    int data;
    struct BiNode node;

} ElemType;
Status CreateTree(BiTree &T)
{

    char ch;
    scanf("%c",&ch);
    if(ch=='*')
        T=NULL;
    else
    {
        T=(BiTree)malloc(sizeof(BiNode));
        if(!T)
            exit(OVERFLOW);
        T->data=ch;
        CreateTree(T->lchild);
        CreateTree(T->rchild);

    }
    return OK;
}
BiTree Jude(BiTree T,char x)
{
    BiTree T1;
    if(T)
    {
        if(T->data==x)
            return T;
        else
        {
            T1=Jude(T->lchild,x);
            if(T1)
                return T1;
            else
                return Jude(T->rchild,x);
        }

    }
    return NULL;
}
int height(BiTree T)
{
    int h1,h2;
    if(T)

    {
        h1=height(T->lchild);
        h2=height(T->rchild);
        return h1>h2?h1+1:h2+1;
    }
    else
        return 0;

}
int main()
{
    BiTree T,T1,T2;
    CreateTree(T);
    getchar();//注意换行符
    char a,b;
    scanf("%c",&a);
    scanf("%c",&b);
    int h;

    T1=Jude(T,a);
    T2=Jude(T1,b);
    if(T1&&T2)
    {
        h=height(T1)-height(T2);
        printf("%d",h);

    }
    else
        printf("NO\n");
    return 0;

}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值