题目:
Problem Description
判断两序列是否为同一二叉搜索树序列
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
Output
如果序列相同则输出YES,否则输出NO
Sample Input
2
567432
543267
576342
0
Sample Output
YES
NO
分析:
一道二叉搜索树的题目。将序列转换成二叉搜索树,然后遍历。如果遍历的结果相同,那么是同一颗二叉树。注意没有重复数字。
下方给出了前序遍历的解法。
https://github.com/pusidun/OJ_Answer/tree/master/HDOJ/3791
#include <cstdio> #include <vector> #include <cstring> #include <iostream> using namespace std; //rst1保存第一个树的前序遍历结果,rst2保存后面n个树的前序遍历结果,index为这2个数组的下标 int rst1[11]; int rst2[11]; int index = 0; class BST{ private: struct Node{ int key; Node* left; Node* right; Node(){ this->key = 0; this->left = NULL; this->right = NULL; } Node(int num){ this->key = num; this->left = NULL; this->right = NULL; } }; Node* root; Node* insert(Node* node, int num){ if (node == NULL){ count++; return new Node(num); } if (node->key < num){ node->right = insert(node->right, num); } else if (node->key > num){ node->left = insert(node->left, num); } return node; } //select用来选择前序遍历结果的保存位置 void preOrder(Node* node, int select){ if (node == NULL) return; if (select == 1) rst1[index++] = node->key; else if (select == 2) rst2[index++] = node->key; preOrder(node->left, select); preOrder(node->right, select); } void remove(Node* node){ if (node == NULL) return; remove(node->left); remove(node->right); delete node; } public: int count; BST(){ root = NULL; count = 0; } ~BST(){ remove(root); } void insert(int num){ root = insert(root, num); } void preOrder(int select){ preOrder(root, select); } }; void str2int(char* s, int* arr){ for (int i = 0; s[i] != '