/**************************************************
题目描述:
判断两序列是否为同一二叉搜索树序列
输入:
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
输出:
如果序列相同则输出YES,否则输出NO
样例输入:
2
567432
543267
576342
0
样例输出:
YES
NO
******************************************************/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int N = 10 + 5;
struct BTree {
BTree *left;
BTree *right;
char ch;
BTree():left(NULL), right(NULL) {};
};
void insert(BTree **root, char ch);
void inOrder(BTree *root, string &s);
void freeTree(BTree *root);
int main()
{
string s, res1, res2;
int n;
BTree *root = NULL;
#ifndef ONLINE_JUDGE
ifstream cin("d:\\OJ\\uva_in.txt");
#endif // ONLINE_JUDGE
while (1) {
cin >> n;
if (n == 0)
break;
getline(cin, s);
getline(cin, s);
for (size_t i = 0; i < s.length(); i++) {
insert(&root, s[i]);
}
res1.clear();
inOrder(root, res1);
freeTree(root);
root = NULL;
while (n--) {
getline(cin, s);
for (size_t i = 0; i < s.length(); i++) {
insert(&root, s[i]);
}
res2.clear();
inOrder(root, res2);
//cout << "res1:" << res1 <<endl;
//cout << "res2:" << res2 << endl;
if (res1 == res2)
cout << "YES" << endl;
else
cout << "NO" << endl;
freeTree(root);
root = NULL;
}
}
return 0;
}
void insert(BTree **root, char ch)
{
if (*root == NULL) {
*root = new BTree();
(*root)->ch = ch;
} else if ((*root)->ch < ch) {
insert(&((*root)->right), ch);
} else if ((*root)->ch > ch) {
insert(&((*root)->left), ch);
}
}
void inOrder(BTree *root, string &s)
{
if (!root)
return;
s.append(1, root->ch);
inOrder(root->left, s);
inOrder(root->right, s);
}
void freeTree(BTree *root)
{
if (!root)
return;
freeTree(root->left);
freeTree(root->right);
delete root;
}
题目1009:二叉搜索树

最新推荐文章于 2024-03-07 18:00:00 发布