HDU 3791 BST

HDU 3791

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=3791

题意:

问两颗二叉搜索树是否相同

思路:

构建二叉搜索树。

语法方面需要注意的是,如果对一个指针需要重用,每次都要把它声明成NULL

源码:

#include <cstdio>

#include <cstring>

#include <cstdlib>

#include <cmath>

#include <algorithm>

#include <iostream>

#include <set>

#include <string>

using namespace std;

char str[25];

struct Point

{

    Point *son[2];

    int val, cnt;

    Point(){val = cnt = 0; son[0] = son[1] = NULL;}

};

int cmp(Point *root, int k)

{

    if(root->val == k)

        return -1;

    else if(root->val > k)

        return 1;

    return 0;

}

void cle(Point* &root)

{

    if(root == NULL){

        return;

    }

    if(root->son[0] != NULL)

        cle(root->son[0]);

    if(root->son[1] != NULL)

        cle(root->son[1]);

    delete(root);

}

void in(Point* &root, int k)

{

    if(root == NULL){

        root = new Point();

        root->val = k;

        return;

    }

    int d = cmp(root, k);

    if(d == -1)

        root->cnt++;

    else

        in(root->son[d], k);

}

void build(Point* &root)

{

    scanf("%s", str);

    cle(root);

    for(int i = 0 ; i < (int)strlen(str); i++){

        in(root, str[i] - '0');

    }

}

bool cmp2(Point* root, Point* temp)

{

    if(root == NULL && temp == NULL){

//        printf("first\n");

        return true;

    }

    if(root == NULL || temp == NULL){

//        printf("second\n");

        return false;

    }

    if(root->val != temp->val){

//        printf("third\n");

        return false;

    }

    int ans = cmp2(root->son[0], temp->son[0]) * cmp2(root->son[1], temp->son[1]);

//    printf("forth\n");

    return ans;

}

int main()

{

    int n;

    while(scanf("%d", &n) != EOF && n){

        Point *root, *temp;

        root = NULL;

        build(root);

        for(int i = 0 ; i < n ; i++){

            temp = NULL;

            build(temp);

            if(cmp2(root, temp))

                printf("YES\n");

            else

                printf("NO\n");

        }

    }

    return 0;

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值