判断不同输入序列是否为同一棵二叉搜索树的方法之一

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

//flag 1 :未路过 0已路过
struct tree{
    int data;
    struct tree *left ,*right;
    int flag;
};

struct tree *newnode(int n){//建立头结点
    struct tree*p;
    p=(struct tree*)malloc(sizeof(struct tree));
    p->data=n;
    p->flag=1;
    p->left=p->right=NULL;
    return p;
}

struct tree*insert(struct tree*head,int n){//插入
    struct tree*new;
    if(n>head->data&&head->right!=NULL)
        head->right=insert(head->right,n);
    else if(n<head->data&&head->left!=NULL)
        head->left=insert(head->left,n);
    else{
        new=(struct tree*)malloc(sizeof(struct tree));
        new->data=n;
        new->left=NULL;
        new->right=NULL;
        new->flag=1;
        if(n>head->data)
            head->right=new;
        else
            head->left=new;
    }
    return head;
}

struct tree* madetree(int N){
    int i,n;
    struct tree*head;
    scanf("%d",&n);
    head=newnode(n);
    for(i=1;i<N;i++){
        scanf("%d",&n);
        head=insert(head,n);
    }
    return head;
}

int check(struct tree*head,int n){//返回0代表该数字出现的序列不符合,1则当前数字的序列符合
    if(!head->flag){
        if(n>head->data)
            return(check(head->right,n));
        if(n<head->data)
            return(check(head->left,n));
    }
    else{
        if(n==head->data)
            head->flag=0;
        else
            return 0;
    }
    return 1;
}

struct tree* chongzhi(struct tree*head){//路径标示为1
    head->flag=1;
    if(head->left)
        head->left=chongzhi(head->left);
    if(head->right)
        head->right=chongzhi(head->right);
    return head;
}
int  panduan(struct tree*head,int N){//
    int i,n;
    int result=1;
    for(i=0;i<N;i++){
        scanf("%d",&n);
        if(result)
            result=check(head,n);
    }
    head=chongzhi(head);
    return result;
}
int main(){
    int N,L;
    struct tree* head;
    scanf("%d",&N);
    while(N){
    scanf("%d",&L);
    head=madetree(N);//
        while(L--){
        if(panduan(head,N))//
            printf("Yes\n");
        else
            printf("No\n");
        }
    free(head);
    scanf("%d",&N);
    }
    return 0;
}

来源于中国幕课-数据结构–<陈越老师>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值