http://acm.hdu.edu.cn/showproblem.php?pid=3791
题意:给你一个标准串,此串可以构成一个二叉搜索树,接着是n个比较串,求问这两个串是否可以构成同一个二叉搜索树。
思路:主要考查二叉排序树的建立。由于二叉排序树的中序遍历都是升序,只要总的元素值一样最后结果就一样,故没有判断的必要。而中序+前序可以确定一棵树,故只要判断前序序列是否相等即可得出是否为同一颗树(若总的元素值不一样前序序列也不会一样)。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <stack>
#include <queue>
#include <cmath>
#include <climits>
using namespace std;
const int MAXN = 1005;
const int INF = INT_MAX;
struct Treenode{
char data;
Treenode* leftchild;
Treenode* rightchild;
Treenode(char c) : data(c), leftchild(NULL), rightchild(NULL) {}
};
Treenode* Insert(Treenode* root, char value){
if(root == NULL){
root = new Treenode(value);
return root;
}
if(value < root->data) root->leftchild = Insert(root->leftchild, value);
if(value > root->data) root->rightchild = Insert(root->rightchild, value);
return root;
}
void PreOrder(Treenode* root, string &str){
if(root == NULL) return;
str += root->data;
PreOrder(root->leftchild, str);
PreOrder(root->rightchild, str);
return;
}
string Build(string str){
Treenode* root = NULL;
for(int i = 0; i < str.size(); i++){
root = Insert(root, str[i]);
}
string ans = "";
PreOrder(root, ans);
return ans;
}
int main(){
// freopen("in.txt", "r", stdin);
int n;
string standard, sample;
while(~scanf("%d", &n)){
if(n == 0) break;
cin >> standard;
string ans1 = Build(standard);
//cout << ans1 << endl;
while(n--){
cin >> sample;
string ans2 = Build(sample);
//cout << ans2 << endl;
if(ans1 == ans2) printf("YES\n");
else printf("NO\n");
}
}
return 0;
}