HDU 3791 二叉搜索树 题解

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



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值