花了很久的时间才过,写下我的写题心得
题目如下:
思路就是,先建一棵树,然后其他就跟其比较判断。代码如下:
//将第一行建为一棵二叉搜索树然后将其他的依次去匹配判断
#include<iostream>
using namespace std;
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
int flag;//这一步很重要,用flag来判断匹配时是否查找过
}TreeNode;
TreeNode* addBST(TreeNode* root, int val) {//往二叉搜索树中插节点,我这里是插成叶节点
if (root == nullptr) {
TreeNode* root = new TreeNode;
root->val = val;
root->flag = 0;
root->left = nullptr;
root->right = nullptr;
return root;
}
else if (root->val > val) {
root->left = addBST(root->left, val);
}
else if (root->val < val) {
root->right = addBST(root->right, val);
}
return root;
}
bool boolBST(TreeNode* root, int val) {//判断是否搜索过
if (root->flag) {
//搜索过就判断大小,大往右,小往左,等于就是错的
if (root->val > val) return boolBST(root->left, val);
else if (root->val < val) return boolBST(root->right, val);
else return false;
}
else {
//没搜索过,相等就标为1,不相等就是错的
if (root->val == val) {
root->flag = 1;
return true;
}
else return false;
}
}
bool isEqual(TreeNode* T, int N) {
int val, flag = 1;
while (N--) {
cin >> val;
if (!boolBST(T, val)) {
flag = 0; //一开始写的时候,在这直接就返回bool型了,导致段错误 :(
}
}
if (!flag) return false;
return true;
}
TreeNode* creatBST(int N) {
int rval;
cin >> rval;
TreeNode* root = new TreeNode;
root->val = rval;
root->flag = 0;
root->left = nullptr;
root->right = nullptr;
N--;
while (N--) {
int val;
cin >> val;
root = addBST(root, val);
}
return root;
}
void flagBST(TreeNode* root) {
if (root == nullptr) return;
root->flag = 0;
flagBST(root->left);
flagBST(root->right);//更新旗帜为0
}
int main() {
int N, L;
while (cin >> N && N) {
cin >> L;
TreeNode* T = creatBST(N);
while (L--) {
if (isEqual(T, N)) cout << "Yes" << endl;
else cout << "No" << endl;
flagBST(T);
}
}
return 0;
}
提交的结果: