hdu 3791 二叉排序树水题

一开始想到的办法,对每个序列建立二叉排序树后先根遍历看得到的序列是否相同即可。打完后忽然想到,其实既然我用数组存下了二叉树,那么直接比较树是否完全一样就可以了的,算了就这样吧,以后再打……

/*
* hdu3791/linux.cpp
* Created on: 2011-9-6
* Author : ben
*/
#include
<cstdio>
#include
<cstdlib>
#include
<cstring>
#include
<cmath>
#include
<algorithm>
using namespace std;

typedef
struct Node {
char num;
Node
*pLeft, *pRight;
} Node;

const int MAX_NODE = 200;
const int MAXN = 30;
int nCount;
Node Tree[MAX_NODE];
char orilist[MAXN], newlist[MAXN];
int oriindex, newindex;

void Create(Node *pRoot, char num) {
if (pRoot->num == 0) {
pRoot
->num = num;
return;
}
if (num > pRoot->num) {
if (pRoot->pLeft == 0) {
nCount
++;
pRoot
->pLeft = Tree + nCount;
}
Create(pRoot
->pLeft, num);
}
else {
if (pRoot->pRight == 0) {
nCount
++;
pRoot
->pRight = Tree + nCount;
}
Create(pRoot
->pRight, num);
}
}

void getori(Node *pRoot) {
orilist[oriindex
++] = pRoot->num;
if (pRoot->pLeft) {
getori(pRoot
->pLeft);
}
if (pRoot->pRight) {
getori(pRoot
->pRight);
}
}

void getnew(Node *pRoot) {
newlist[newindex
++] = pRoot->num;
if (pRoot->pLeft) {
getnew(pRoot
->pLeft);
}
if (pRoot->pRight) {
getnew(pRoot
->pRight);
}
}

void work() {
int n;
char c;
while (scanf("%d", &n) == 1) {
getchar();
for (int i = 0; i < MAX_NODE; i++) {
Tree[i].num
= 0;
Tree[i].pLeft
= 0;
Tree[i].pRight
= 0;
}
nCount
= 0;
while ((c = getchar()) > ' ') {
Create(Tree, c);
}
oriindex
= 0;
getori(Tree);
for (int i = 0; i < n; i++) {
for (int i = 0; i < MAX_NODE; i++) {
Tree[i].num
= 0;
Tree[i].pLeft
= 0;
Tree[i].pRight
= 0;
}
nCount
= 0;
while ((c = getchar()) > ' ') {
Create(Tree, c);
}
newindex
= 0;
getnew(Tree);
if (oriindex != newindex) {
puts(
"NO");
continue;
}
int j = 0;
for (j = 0; j < newindex; j++) {
if (orilist[j] != newlist[j]) {
break;
}
}
if (j == newindex) {
puts(
"YES");
}
else {
puts(
"NO");
}
}
}
}

int main() {
#ifndef ONLINE_JUDGE
freopen(
"data.in", "r", stdin);
#endif
work();
return 0;
}
原文地址:https://www.cnblogs.com/moonbay/p/2169137.html