I got the template (which others on this website said worked) from here
I really cannot see an issue with anything here. I've been looking at it for about 3 hours. The infinite loops is the main error here in the balancing method, and it is because it passes through each of the if statements without finding any matching qualities. Also, the error in the RBT that needs correcting is that there are 2 red nodes in a row.
Constructor
MovieTree:: MovieTree(){
nil = new MovieNode;
nil->isRed=false;
root= nil;
root->left=nil;
root->right=nil;
}
Add method
void MovieTree::addMovieNode(int ranking, std::string title, int year, int quantity){
cout<<title<<" added."<<endl;
if(root == nil){
root =new MovieNode(ranking, title, year, quantity);
root->isRed=false;
root->left = nil;
root->right = nil;
root->parent = nil;
int b = rbValid(root);
cout<<b<<endl;
return;
}
MovieNode *temp = root; //root
MovieNode* parent = nil; //parent
//node is node to add
while(temp != nil){//gets to bottom of tree
parent = temp;//sets temp to parent of location for where node is added
if(title < temp->title){
temp=temp->left;
}
else{temp=temp->right;}
}
MovieNode *node;
if(title < parent->title){//adds to either left or right
cout<<"added to left"<<endl;
node = new MovieNode(ranking, title, year, quantity);
node->left = nil;
node->right = nil;
node->parent = nil;
node->isRed=true;
parent->left = node;
node->parent=parent;
}
else{
cout<<"added to right"<<endl;
node = new MovieNode(ranking, title, year, quantity);
node->left = nil;
node->right = nil;
node->parent = nil;
node->isRed=true;
parent->right=node;
node->parent=parent;
}
int a = rbValid(root);
cout<<a<<endl;
rbAddFixup(node);//seg fault is here
}
Balancing Method
void MovieTree::rbAddFixup(MovieNode * node ){
if(node->parent->isRed==true){
cout<<"parent is red"<<endl;
}
while(node != root && node->parent->isRed==true){
if(node->parent == node->parent->parent->left){//first event doesn't apply
MovieNode *uncle = node->parent->parent->right;
if(uncle ->isRed == true){
node->parent->isRed=false;//begin rbcase1
uncle->isRed=false;
node->parent->parent->isRed=true;//end rbcase1
node=node->parent->parent;
}
else{
if(node == node->parent->right){
node=node->parent;
leftRotate(node);
node->parent->isRed=false; //case3
node->parent->parent->isRed=true;
rightRotate(node->parent->parent);//end case3
}
}
}else{
MovieNode *uncle = node->parent->parent->left;
if(uncle ->isRed == true){
node->parent->isRed=false;
uncle->isRed=false;
node->parent->parent->isRed=true;
node=node->parent->parent;
}
else{
//infinite loop happens here
if(node == node->parent->left){
node=node->parent;
rightRotate(node);
node->parent->isRed=false;
node->parent->parent->isRed=true;
leftRotate(node->parent->parent);
}
}
}
}
root->isRed=false;
}