Hello all,
I'm currently trying to implement a Red-Black Tree, but for now I am using the Vanilla BST insertion implementation (baby steps). I am getting a Segmentation Fault inserting the elements. Here is what I have:
node.h:
Code:
#ifndef Header_h
#define Header_h
#include <iostream>
template <class T>
class RBNode {
public:
T data;
/* - red = 1
- black = 0 */
int color;
/* - index 0 is the left node
- index 1 is the right node*/
RBNode *link[2];
RBNode(const T& d = T(), RBNode *l = NULL,
RBNode *r = NULL, int c = 1) {
data = d;
link[0] = l;
link[1] = r;
color = c;
}
};
#endif
tree.h:
Code:
#ifndef tree_h
#define tree_h
#include "node.h"
template <class T>
class RBTree {
private:
RBNode<T> *root;
void insert_entry(RBNode<T> *&node, const T& entry);
void print_entries(RBNode<T> *node);
void tree_clear(RBNode<T> *&r) {
if(r != NULL){
tree_clear(r->link[0]);
tree_clear(r->link[1]);
delete r;
r = NULL;
}
}
public:
RBTree() {
root = NULL;
}
~RBTree() {
tree_clear(root);
}
void insert(const T& entry);
void print();
};
template <class T>
void RBTree<T>::insert_entry(RBNode<T> *&node, const T& entry) {
if(node == NULL)
node = new RBNode<T>(entry);
else {
int dir = root->data < entry;
insert_entry(root->link[dir], entry);
}
}
template <class T>
void RBTree<T>::print_entries(RBNode<T> *node) {
print_entries(node->link[0]);
std::cout << node->data << " ";
print_entries(node->link[1]);
}
template <class T>
void RBTree<T>::insert(const T& entry) {
insert_entry(root, entry);
}
template <class T>
void RBTree<T>::print() {
print_entries(root);
std::cout << "\n";
}
#endif