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;
}