二叉排序树的判别(耿8.6)

Description

试编写程序,判别给定的二叉树是否为二叉排序树。设此二叉树以二叉链表作存储结构,且树中结点的关键字均不同。

Input

按先序输入二叉树各结点(结点值大于0),其中-1表示取消建立子树结点。

Output

若该二叉树为二叉排序树,则输出yes;否则,输出no。

  • Sample Input 
    12 8 4 -1 -1 10 -1 -1 16 13 -1 -1 18 -1 -1
  • Sample Output
    yes
#include<stdio.h>
#include<stdlib.h>

typedef struct BinNode
{
    int data;
    struct BinNode *lchild;
    struct BinNode *rchild;
}BinNode,*BinTree;

void CreateBinTree(BinNode *tree)
{
    int ch;
    scanf("%d",&ch);
    if(ch == -1)
    {
        tree = NULL;
    }
    else
    {
        tree = (BinTree)malloc(sizeof(BinNode));
        tree->data = ch;
        CreateBinTree(tree->lchild);
        CreateBinTree(tree->rchild);
    }
}

int judge(BinNode *t)
{
    if(!t)
        return 1;
    else if(!(t->lchild) && !(t->rchild))
        return 1;
    else if((t->lchild) && !(t->rchild))
    {
        if(t->lchild->data>t->data)
            return 0;
        else
            return judge(t->lchild);
    }
    else if((t->rchild) && !(t->lchild))
    {
        if(t->rchild->data<t->data)
            return 0;
        else
            return judge(t->rchild);
    }
    else
    {
        if((t->lchild->data>t->data) || (t->rchild->data<t->data))
            return 0;
        else
            return ( judge(t->lchild) && judge(t->rchild) );
    }
}

int main()
{
    BinNode *T = NULL;
    CreateBinTree(T);
    int flag=judge(T);
    if(flag)printf("yes\n");
    else printf("no\n");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值