36-题目1009:二叉搜索树

来源:互联网 发布:ubuntu install git 编辑:程序博客网 时间:2024/05/16 08:58

http://ac.jobdu.com/problem.php?pid=1009

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

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

样例输入:
25674325432675763420
样例输出:
YESNO

用建立二叉排序树的方法不知道怎么输出前序后序,没法比较;

用静态数组的方法,最大的数组长度有1023,太稀疏了,比如将还每次都要从0开始比较,时间复杂度太高。。。

但是我看到的大神的静态数组的做法,算法和我相同,但是优化了静态数组的比较方式,虽然时间复杂度还是比较高。。。。

#include<stdio.h>#include<stdlib.h>#include<string>#include<iostream>#include<fstream>using namespace std;void CreatBitree(string str, int a[]){int len = str.length();for (int i = 0; i < len; i++){int temp = str[i] - '0';for (int j = 1; j <= 1023; j++){if (a[j] == -1)    //找到要存放的位置{a[j] = temp;break;}else if (a[j] < temp) //存到右子树j = 2 * j + 1;elsej = 2 * j;}}}int main(){int n, i;ifstream cin("data.txt");while (cin >> n && n != 0){string str;cin >> str;int a[1024];for (i = 0; i < 1024; i++)a[i] = -1;CreatBitree(str, a);while (n--){string str2;cin >> str2;int b[1024];for (i = 0; i < 1024; i++)b[i] = -1;CreatBitree(str2, b);for (i = 0; i < 1024; i++)if (a[i] != b[i]) break;if (i == 1024) cout << "YES" << endl;else cout << "NO" << endl;}}system("pause");return 0;}



0 0
原创粉丝点击