二叉搜索树(hdu 3791)

本文介绍了一个简单的二叉搜索树实现,包括节点的插入及中序遍历和后序遍历的方法,并通过比较两个树的遍历结果来判断它们是否相同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

特别基础的题……

#include<bits/stdc++.h>
using namespace std;
int cnt;
char a[15],b[15],c[15];
typedef struct tree
{
    int num;
    tree *lc;
    tree *rc;
} tree;
tree *root;
tree *Insert(tree *s,int x)
{
    tree *t;
    if(s==NULL)
    {
        t=new tree;
        t->lc=NULL;
        t->rc=NULL;
        t->num=x;
        s=t;
    }
    else
    {
        if(x<= s->num)
            s->lc=Insert(s->lc,x);
        else
            s->rc=Insert(s->rc,x);
    }
    return s;
}
void libian(tree *root)
{
    if(root)
    {
        b[cnt++]=root->num+'0';
        libian(root->lc);
        libian(root->rc);
    }
}
void Libian(tree *root)
{
    if(root)
    {
        c[cnt++]=root->num+'0';
        Libian(root->lc);
        Libian(root->rc);
    }
}
int main()
{
    int n;
    while(scanf("%d",&n)==1&&n)
    {
        cnt=0;
        root=NULL;
        scanf("%s",a);
        for(int i=0; a[i]!='\0'; i++)
            root=Insert(root,a[i]-'0');
        libian(root);
        b[cnt]='\0';
        while(n--)
        {
            cnt=0;
            root=NULL;
            scanf("%s",a);
            for(int i=0; a[i]!='\0'; i++)
                root=Insert(root,a[i]-'0');
            Libian(root);
            c[cnt]='\0';
            if(strcmp(b,c)==0) printf("YES\n");
            else printf("NO\n");
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值