这是关于Stack Overflow的第一个问题!
我必须实现一个红黑树,但由于某种原因,我在运行代码时遇到了分段错误。我已经经历了一千次,但似乎无法弄清楚我哪里出错了。希望其他人可以选择我错过的东西。
程序从文本文件中读取单词并尝试将每个单词插入到RB树中。我编写了一个类似的程序,使用字符串比较运算符插入二叉搜索树,所以我不认为这是问题。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
enum color {red,black};
struct node{
enum color color;
string value;
node *leftChild,*rightChild,*parent;
};
class RBT{
private:
string filename;
node* root = NULL;
int readfile(){//read file and insert each word into BST
ifstream file;
file.open (filename.c_str());
if (!file.is_open()) return 1;
string word;
while (file >> word){// for each word in file
insert(word);
}
return 0;
}
void left_rotate(node* x){
node* y = x->rightChild;
x->rightChild = y->leftChild;
if(y->leftChild != NULL)
y->leftChild->parent = x;
y->parent = x->parent;
if(x->parent == NULL)
root = y;
else if(x->parent->leftChild == x)
x->parent->leftChild = y;
else
x->parent->rightChild = y;
y->leftChild = x;
x->parent = y;
}
void right_rotate(node* y){
node* x = y->leftChild;
y->leftChild = x->rightChild;
if(x->rightChild != NULL)
x->rightChild->parent = y;
x->parent = y->parent;
if(y->parent == NULL)
root = x;
else if(y->parent->leftChild == y)
y->parent->leftChild = x;
else
y->parent->rightChild = x;
x->rightChild = y;
y->parent = x;
}
void insert_fix(node* z){
while (z->parent->color == red) {
if (z->parent == z->parent->parent->leftChild) {
node* y = z->parent->parent->rightChild;
if(y->color == red){
z->parent->color = black;
y->color = black;
z->parent->parent->color = red;
z = z->parent->parent;
}
else{
if(z == z->parent->rightChild){
z = z->parent;
left_rotate(z);
}
z->parent->color = black;
z->parent->parent->color = red;
right_rotate(z->parent->parent);
}
}
else{
node* y = z->parent->parent->leftChild;
if(y->color == red){
z->parent->color = black;
y->color = black;
z->parent->parent->color = red;
z = z->parent->parent;
}
else {
if(z == z->parent->leftChild){
z = z->parent;
right_rotate(z);
}
z->parent->color = black;
z->parent->parent->color = red;
left_rotate(z->parent->parent);
}
}
}
(root)->color = black;
}
void tree_insert(node* Z){
node* y = NULL;
node* x = root;
while(x != NULL) {
y = x;
if(Z->value < x->value){
x = x->leftChild;
}
else if (Z->value > x->value){
x = x->rightChild;
}
else{
return;
}
}
Z->parent = y;
if(y == NULL)
root = Z;
else if(Z->value < y->value)
y->leftChild = Z;
else
y->rightChild = Z;
Z->leftChild = NULL;
Z->rightChild = NULL;
Z->color = red;
insert_fix(Z);
}
public:
RBT(string _filename);
void insert(string S){
node* strNode = new node;
strNode->value=S;
strNode->leftChild=NULL;
strNode->rightChild=NULL;
strNode->parent=NULL;
tree_insert(strNode);
}
};
RBT::RBT(string _filename){
filename = _filename;
root = new node;
readfile();
}
int main(){
RBT rbt1 ("words.txt");
}