HDU 3791 二叉搜索树 题解

来源:互联网 发布:淘宝改标题会降权吗 编辑:程序博客网 时间:2024/04/29 22:52

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

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

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

Sample Input
25674325432675763420
 

Sample Output
YESNO

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

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

#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
原创粉丝点击