判断二叉排序树

此题为西电数据结构课程上机题
//判断二叉排序树函数
int inorder(bitree *p)
{
    if(p!=NULL)
    {
        if(!inorder(p->lchild))return 0;
        if(flag)flag=0;
        else if(p->key<last)return 0;  //{puts("no");exit(0);}此时不用!inorder判断,但是会直接退出程序 
        last=p->key;
        if(!inorder(p->rchild))return 0;
    }
    return 1;
} 
全部代码:
//判断二叉排序树的程序代码
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
//二叉链表的结构类型定义
const int maxsize=1024;
typedef int keytype;
typedef struct node
{
    keytype key;
    struct node *lchild,*rchild;
}bitree;

bitree*creattree();
void preorder(bitree*);
int inorder(bitree*);
keytype last;
int flag=1;

int main()
{
    bitree*pb;
    pb=creattree();
    preorder(pb);
    printf("\n");
    if(inorder(pb))printf("是二叉排序树!\n");
    else printf("no");
}

//二叉树的建立
bitree*creattree()
{
    keytype x;
    bitree*Q[maxsize];
    int front,rear;
    bitree*root,*s;
    root=NULL;
    front=1;rear=0;
    printf("按层次输入二叉排序树的整型结点数据,0表示虚结点,-1表示结束:\n");
    scanf("%d",&x);//输入0表示虚结点,-1表示结束
    while(x!=-1)
    {
        s=NULL;
        if(x!=0)
        {
            s=(bitree*)malloc(sizeof(bitree));
            s->key=x;
            s->lchild=NULL;
            s->rchild=NULL;
        }
        rear++;
        Q[rear]=s;
        if(rear==1)root=s;
        else
        {
            if(s&&Q[front])
                if(rear%2==0)Q[front]->lchild=s;
                else Q[front]->rchild=s;
            if(rear%2==1)front++;
        }
        scanf("%d",&x);;
    }
    return root;
}

//二叉树的输出
void preorder(bitree*p)
{
    if(p!=NULL)
    {
        printf("%d",p->key);
        if(p->lchild!=NULL||p->rchild!=NULL)
        {
            printf("(");
            preorder(p->lchild);
            if(p->rchild!=NULL) printf(",");
            preorder(p->rchild);
            printf(")");
        }
    }
}

//添加判断二叉排序树算法
int inorder(bitree *p)
{
    if(p!=NULL)
    {
        if(!inorder(p->lchild))return 0;
        if(flag)flag=0;
        else if(p->key<last)return 0;  //{puts("no");exit(0);}此时不用!inorder判断,但是会直接退出程序 
        last=p->key;
        if(!inorder(p->rchild))return 0;
    }
    return 1;
} 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。