HDU二叉搜索树

#include <iostream>
#include <cstring>

using namespace std;

char a[16];

struct node
{
    int v;
    node* l;
    node* r;
    node(int v = 0, node* l = NULL, node* r = NULL)
    {
        this->v = v;
        this->l = l;
        this->r = r;
    }
};
void build_tree(int a, node*& s)
{
    if (a > s->v)
    {
        if (s->r == NULL) s->r = new node(a);
        else build_tree(a, s->r);
    }
    else 
    {
        if (s->l == NULL) s->l = new node(a);
        else build_tree(a, s->l);
    }
}
bool cmp(node* x, node* y)
{
    if (x->v != y->v) return false;
    if (x->l == NULL && y->l == NULL && x->r == NULL && y->r == NULL) return true;
    if (x->l == NULL && y->l == NULL) return cmp(x->r, y->r);
    if (x->r == NULL && y->r == NULL) return cmp(x->l, y->l);
    if (x->l != NULL && y->l != NULL && x->r != NULL && y->r != NULL) return (cmp(x->r, y->r) && cmp(x->l, y->l));
    return false;
}
void remove_tree(node*& root)
{
    if (root == NULL) return;
    remove_tree(root->l);
    remove_tree(root->r);
    delete root;
}

int main()
{
    while (1)
    {
        int n;
        cin >> n;
        if (n == 0) break;
        cin >> a;
        int l = strlen(a);
        node* root=new node(a[0] - '0');
        for (int i = 1; i < l; i++)
            build_tree(a[i] - '0', root);
        for (int i = 0; i < n; i++)
        {
            char b[16];
            cin >> b;
            if (l != strlen(b))
            {
                cout << "NO" << endl;
                continue;
            }
            node* temp = new node(a[0] - '0');
            for (int j = 1; j < l; j++)
                build_tree(b[j] - '0', temp);
            if (cmp(root, temp)) cout << "YES" << endl;
            else cout << "NO" << endl;
            remove_tree(temp);
        }
        remove_tree(root);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值