HDU-3791-判断一棵树是不是二叉搜索树

来源:互联网 发布:域名注册哪家比较好 编辑:程序博客网 时间:2024/06/05 09:49

二叉搜索树

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2538    Accepted Submission(s): 1102

Problem Description
判断两序列是否为同一二叉搜索树序列
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
Output
如果序列相同则输出YES,否则输出NO
Sample Input
25674325432675763420
Sample Output
YESNO
Source
浙大计算机研究生复试上机考试-2010年
 

思路:

         用数组建立一棵二叉搜索树,然后,比较这两棵树是否相同即可。

/*First time,I used inorde and preorder to judge if it's Yes or No,but Time Limit Exceeded,Second time,I change to isEqual(),then ,it's done.*/#include <iostream>#include <string>#include <limits.h>using namespace std;struct node{char key;node* left;node* right;node(char k):key(k),left(NULL),right(NULL){}};void insert(node** root,node* z){node *y = NULL, *x = *root;while(x){y = x;if (y->key < z->key)x = x->right;else x = x->left;}if (y == NULL)*root = z;else if (y->key < z->key)y->right =z;elsey->left = z;}void Del(node* root){if (root != NULL){Del(root->left);Del(root->right);delete root; //Can't exchange order,can't put delete front or middle}}bool isEqual(node* root1,node* root2){if (root1 != NULL && root2 != NULL){if (root1->key != root2->key)return false;return (isEqual(root1->left,root2->left) && isEqual(root1->right,root2->right));}else{if (root1 == NULL && root2 == NULL)return true;elsereturn false;}}int main(){int T,i;//string line, stdIn = "", stdPre = "", In = "", Pre = "";string line;node *root1 = NULL,*root2 = NULL;while (cin >> T && T!=0){getchar(); //to get '\n' in the endgetline(cin,line);root1 = NULL;for (i=0; i<line.size(); ++i){insert(&root1,new node(line[i]));}//InOrder(root,stdIn);//PreOrder(root,stdPre);//Del(root); // void Memory leakswhile (T--){getline(cin,line);root2 = NULL;for (i=0; i<line.size(); ++i){insert(&root2,new node(line[i]));}if (isEqual(root1,root2))cout << "YES" << endl;elsecout << "NO" << endl;//In = "";//InOrder(root,In);//Del(root);//if ( In != stdIn )//{//cout << "NO" << endl;//continue;//}//root = NULL;//Pre = "";//PreOrder(root,Pre);//Del(root);//if (Pre != stdPre )//{//cout <<"NO" << endl;//continue;//}//cout << "YES" << endl;}}return 0;}/*void InOrder(node* root,string& str){if( root != NULL){InOrder(root->left, str);str.push_back(root->key);InOrder(root->right, str);}}void PreOrder(node* root,string& str){if( root != NULL){str.push_back(root->key);PreOrder(root->left,str);PreOrder(root->right,str);}}*/


0 0