Search code examples
c++red-black-tree

How to create the sentinel NIL object in a red black tree in C++?


I want to implement a red black tree but I'm struggling with the basic steps. I'm used to just using structs but now I want to make it clean and use Classes.

I want to create a special object NIL (a member in the tree?) (NIL is colored black and all nodes refer to this one single object, in CLRS it says "T.NIL is an object with the same attributes as an ordinary node, its color is black and its left, right and p attributes can take arbitrary values", "we use one sentinel T.nil to represent all the NILs")

How I do set the left, right, p to NIL? Should NIL be created a separate singleton class first and then used in the tree definition? I'm getting errors now when I assign to T.NIL (comments)

#include <iostream>
enum color_t {red, black};

class Tree; // declare first
Tree *T;

class Node { // could be a struct!
public:
    int data;
    color_t color = red;
    Node *left;
    Node *right;
    Node *parent;
    Node() { // default constructor
        left = T->NIL; // ERROR: Member access into incomplete type
        right = T->NIL; // ERROR: Member access into incomplete type
        parent = T->NIL;  // ERROR: Member access into incomplete type
    }
    Node(int d, color_t c) { // if data and color are known
        Node();
        data = d;
        color = c;
    }
};

class Tree {
public:
    Node *root;
    Node *NIL;
    Tree();
    void insert(int d);
    void leftRotate(Node *x);
};

Tree::Tree() {
    NIL = new Node();
    NIL->color = black;
    root = NIL;
} 

Solution

  • You need to move the body of Node::Node() further down in your code; anywhere after class Tree as been defined (at the point you have it, Tree has only been declared).