1009.二叉搜索树

来源:互联网 发布:淘宝货到付款卖家 编辑:程序博客网 时间:2024/06/05 21:55
题目描述:
判断两序列是否为同一二叉搜索树序列
输入:
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
输出:
如果序列相同则输出YES,否则输出NO
样例输入:
2
567432
543267
576342
0
样例输出:
YES

NO


拿出N年前写过的二叉树代码稍稍修改即AC~

#include <iostream>#include <string>#include <fstream>using namespace std;struct BinaryNode{int elem;BinaryNode *left;BinaryNode *right;BinaryNode(int e = 0, BinaryNode *l = NULL, BinaryNode *r = NULL):elem(e),left(l),right(r){}};class BinaryTree{private:BinaryNode *root;void insert(int x, BinaryNode * &t) //important!{if(t == NULL)t = new BinaryNode(x,NULL,NULL);else if(x < t->elem)insert(x,t->left);else if(t->elem < x)insert(x,t->right);else; //如果找到一样的则不处理}void qianxuprint(BinaryNode *root) const{if(root == NULL)return;cout << root->elem << " ";qianxuprint(root->left);qianxuprint(root->right);}void zhongxuprint(BinaryNode *root) const{if(root == NULL)return;zhongxuprint(root->left);cout << root->elem << " ";zhongxuprint(root->right);}void houxuprint(BinaryNode *root) const{if(root == NULL)return;houxuprint(root->left);houxuprint(root->right);cout << root->elem << " ";}public:BinaryTree(BinaryNode *r = NULL):root(r){}BinaryNode* Root()  const{return root;}void insert(int x){insert(x,root);}void qianxuprint() const{qianxuprint(root);}void zhongxuprint() const{zhongxuprint(root);}void houxuprint() const{houxuprint(root);}};bool compare(BinaryNode *root1, BinaryNode *root2){if(root1 == NULL && root2 == NULL)return true;else if(root1 == NULL && root2 != NULL)return false;else if(root1 != NULL && root2 == NULL)return false;else if(root1->elem != root2->elem)return false;return compare(root1->left,root2->left) && compare(root1->right,root2->right);}int main(){int N;while(cin >> N && N != 0){string str;cin >> str;BinaryTree *tree = new BinaryTree;for(int i = 0; i != str.size(); ++i)tree->insert(str[i] - '0');for(int i = 0; i != N; ++i){cin >> str;BinaryTree *tree1 = new BinaryTree;for(int i = 0; i != str.size(); ++i)tree1->insert(str[i] - '0');if(compare(tree->Root(),tree1->Root()))cout << "YES" << endl;elsecout << "NO" << endl;delete tree1;}delete tree;}return 0;}




0 0
原创粉丝点击