hdu3791 二叉搜索树(BST的建立)

 

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

 

 

 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值