04-树4 是否同一棵二叉搜索树(25 point(s))
给定一个插入序列就可以唯一确定一棵二叉搜索树。然而,一棵给定的二叉搜索树却可以由多种不同的插入序列得到。例如分别按照序列{2, 1, 3}和{2, 3, 1}插入初始为空的二叉搜索树,都得到一样的结果。于是对于输入的各种插入序列,你需要判断它们是否能生成一样的二叉搜索树。 输入格式:
输入包含若干组测试数据。每组数据的第1行给出两个正整数N (≤10)和L,分别是每个序列插入元素的个数和需要检查的序列个数。第2行给出N个以空格分隔的正整数,作为初始插入序列。最后L行,每行给出N个插入的元素,属于L个需要检查的序列。
简单起见,我们保证每个插入序列都是1到N的一个排列。当读到N为0时,标志输入结束,这组数据不要处理。 输出格式:
对每一组需要检查的序列,如果其生成的二叉搜索树跟对应的初始序列生成的一样,输出“Yes”,否则输出“No”。 输入样例:
4 2 3 1 4 2 3 4 1 2 3 2 4 1 2 1 2 1 1 2 0
输出样例:
Yes No No
思路
因为 数据比较小 直接采用 满二叉树 的数组 建树方式
然后 用一个字符串 保存其 层序遍历结果
然后 之后每一次 都重复这个操作 只要检验 得到 层序遍历结果的 字符串 是否相同 就可以了
AC代码
#include <cstdio> #include <cstring> #include <ctype.h> #include <cstdlib> #include <cmath> #include <climits> #include <ctime> #include <iostream> #include <algorithm> #include <deque> #include <vector> #include <queue> #include <string> #include <map> #include <stack> #include <set> #include <numeric> #include <sstream> #include <iomanip> #include <limits> #define CLR(a) memset(a, 0, sizeof(a)) #define pb push_back using namespace std; typedef long long ll; typedef long double ld; typedef unsigned long long ull; typedef pair <int, int> pii; typedef pair <ll, ll> pll; typedef pair<string, int> psi; typedef pair<string, string> pss; const double PI = 3.14159265358979323846264338327; const double E = exp(1); const double eps = 1e-30; const int INF = 0x3f3f3f3f; const int maxn = 1e3 + 5; const int MOD = 1e9 + 7; int arr[maxn]; int n, l; string Build() { string temp = ""; CLR(arr); int num; scanf("%d", &arr[1]); int len = 1; for (int i = 1; i < n; i++) { scanf("%d", &num); for (int j = 1; ; ) { if (arr[j] != 0) { if (num > arr[j]) j = j * 2 + 1; else j *= 2; } else { arr[j] = num; if (j > len) len = j; break; } } } for (int i = 0; i <= len; i++) { if (arr[i]) temp += arr[i] + '0'; } return temp; } int main() { while (scanf("%d", &n) && n) { scanf("%d", &l); string st = Build(); for (int i = 0; i < l; i++) { string temp = Build(); if (temp == st) printf("Yes\n"); else printf("No\n"); } } }转载于:https://www.cnblogs.com/Dup4/p/9433170.html
