原题链接
源代码
/*
判断是否为同一棵BST:
如果每次搜索所经过的点在前面均出现过,则一致
否则,遇到了之前没有访问过的点,两棵树一定不一致
*/
#include<iostream>
using namespace std;
int n;
struct node{
int data;
node* left;
node* right;
bool flag; //是否已经访问过了
};
bool check(node* root, int x){
//在BST中查找元素值为data的结点,并且观察找到之前的结点是否都已经访问过了
if(root->flag){
if(x < root->data) check(root->left, x);
else if(x > root->data) check(root->right, x);
else return false;//出现重复元素,认为是不一致的树
}
else{
if(root->data == x){
root->flag = true;
return true;
}
else return false;
}
}
bool judge(node* root){
int v;
bool same = true;//same的目的是为了把n个数读完
//第一个是根,如果不相同,肯定不是一棵树
cin>>v;
if(root->data != v) same = false;
else root->flag = true;
for(int i=1; i<n; i++){
cin>>v;
//如果已经不是一棵树了,没必要check
if(same){
if(!check(root, v))
same = false;
}
}
return same;
}
void reset(node* root){
//清空树的标记
if(root->left) reset(root->left);
if(root->right) reset(root->right);
root->flag = false;
}
void freeTree(node* &root){
//释放树的空间
if(root->left) freeTree(root->left);
if(root->right) freeTree(root->right);
delete root;
root = NULL;
}
void insert(node* &root, int x){
if(root == NULL){
root = new node;
root->data = x;
root->left = root->right = NULL;
return ;
}
if(x < root->data){
insert(root->left, x);
}
else{
insert(root->right, x);
}
}
node* createBST(){
int v;
node* root = NULL;
for(int i=0; i<n; i++){
cin>>v;
insert(root, v);
}
return root;
}
int main(){
int l;
while(cin>>n&&n){
cin>>l;
//建立BST并返回树根
node* root = createBST();
for(int i=0; i<l; i++){
reset(root); //清空树的flag信息
if(judge(root)) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
//释放树的各结点
freeTree(root);
}
return 0;
}
段错误
之前选择的编译器为C++(clang++),一直提示段错误,改为C++(g++)就过了。查阅资料也没发现有什么可能的原因,求解答。