数据结构实验之查找一:二叉排序树


这道题的算法思想是:建立一个初始的排序二叉树,然后比较由输入序列建立的另一个二叉树即可。

代码如下:

#include <stdio.h>
#include <malloc.h>
struct node{/*二叉树的定义*/
    int data;
    struct node *lchild,*rchild;
};
struct node *Createtree(struct node *root,int d){/*创建排序二叉树*/
    if(root==NULL){
        root=(struct node *)malloc(sizeof(struct node));
        root->data=d;
        root->lchild=NULL;
        root->rchild=NULL;
    }
    else{
        if(root->data<d)//输入的元素大于根节点,放入右子树中
            root->rchild=Createtree(root->rchild,d);
        else
            root->lchild=Createtree(root->lchild,d);
    }
    return root;
};
int Compare(struct node* root,struct node *root1){/*判断两个数是否相等*/
    if(root==NULL&&root1==NULL)
        return 1;
    else if((root==NULL&&root1!=NULL)||(root!=NULL&&root1==NULL))
        return 0;
    else if(root->data==root1->data)
            return Compare(root->lchild,root1->lchild)&&Compare(root->rchild,root1->rchild);
    else
        return 0;
}
int main(){
    int n,l,d,i;
    while(scanf("%d %d",&n,&l)&&n!=0){
        struct node *root=NULL;
        for(i=1;i<=n;i++){
            scanf("%d",&d);
            root=Createtree(root,d);
        }
        while(l--){
            struct node *root1=NULL;
            for(i=1;i<=n;i++){
                scanf("%d",&d);
                root1=Createtree(root1,d);
            }
            if(Compare(root,root1))
                printf("Yes\n");
            else
                printf("No\n");
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值