码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 3791 二叉搜索树 题解

时间:2014-07-04 09:15:42      阅读:356      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   使用   数据   

Problem Description
判断两序列是否为同一二叉搜索树序列
 

Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
 

Output
如果序列相同则输出YES,否则输出NO
 

Sample Input
2 567432 543267 576342 0
 

Sample Output
YES NO

一条浙大考研上机题目。考二叉树构建。

直接使用静态数组过了,因为数据不大。

#include <stdio.h>
#include <iostream>
#include <string>
using std::string;
using std::cin;

const int SIZE = (1<<9)+1;
char Tree[SIZE];
char secTree[SIZE];
string root, child;

void constrctTree(char T[], char a, int node = 0)
{
	if (T[node] == 'b')
	{
		T[node] = a;
		return ;
	}
	if (a < T[node]) constrctTree(T, a, node<<1|1);
	else constrctTree(T, a, (node+1)<<1);
}

int main()
{
	int n;
	secTree[1<<9] = '\0';
	Tree[1<<9] = '\0';
	while (scanf("%d", &n) && n != 0)
	{
		for (int i = 0; i < 1<<9; i++) Tree[i] = 'b';
		cin>>root;
		for (int i = 0; i < (int)root.size(); i++)
		{
			constrctTree(Tree, root[i]);
		}
		for (int i = 0; i < n; i++)
		{
			cin>>child;
			if (root.size() != child.size()) puts("NO");
			else
			{
				for (int j = 0; j < 1<<9; j++) secTree[j] = 'b';
				for (int i = 0; i < (int)child.size(); i++)
				{
					constrctTree(secTree, child[i]);
				}
				if (strcmp(Tree, secTree) == 0) puts("YES");
				else puts("NO");
			}
		}
	}
	return 0;
}



HDU 3791 二叉搜索树 题解,布布扣,bubuko.com

HDU 3791 二叉搜索树 题解

标签:des   style   blog   color   使用   数据   

原文地址:http://blog.csdn.net/kenden23/article/details/36649647

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!