是否同一棵二叉搜索樹(段錯誤的原因)

是否同一棵二叉搜索樹

原題鏈接

樹(中)課後練習題1

源代碼

/*
判斷是否爲同一棵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++)就過了。查閱資料也沒發現有什麼可能的原因,求解答。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章