二叉排序树

来源:互联网 发布:男生不追女生 知乎 编辑:程序博客网 时间:2024/06/05 15:09


这道题的算法思想主要是在建立排序二叉树的基础上,对两个二叉树进行比较,需要考虑几种情况。

代码如下:

#include <stdio.h>
#include <malloc.h>
#include <string.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,m,i;
    char a[25],b[25];
    while(scanf("%d",&n)!=EOF&&n!=0){
        scanf("%s",a);
        struct node* root=NULL;
        m=strlen(a);
        for(i=0;i<m;i++){
            int d=a[i]-48;
            root=Createtree(root,d);
        }
        while(n--){
            int t;
            struct node *root1=NULL;
            scanf("%s",b);
            t=strlen(b);
            for(i=0;i<t;i++){
                int k=b[i]-48;
                root1=Createtree(root1,k);
            }
            if(Compare(root,root1))
                printf("YES\n");
            else
                printf("NO\n");
        }
    }
    return 0;
}

0 0