【问题标题】:How to create the sentinel NIL object in a red black tree in C++?如何在 C++ 中的红黑树中创建哨兵 NIL 对象?
【发布时间】:2015-05-18 16:22:05
【问题描述】:

我想实现一棵红黑树,但我正在努力完成基本步骤。我习惯于只使用结构,但现在我想让它变得干净并使用类。

我想创建一个特殊的对象 NIL(树中的一个成员?)(NIL 是黑色的,所有节点都引用这个单个对象,在 CLRS 中它说“T.NIL 是一个具有相同属性的对象一个普通节点,颜色为黑色,left、right、p属性可以取任意值”,“我们用一个sentinel T.nil来表示所有的NIL”)

如何将左、右、p 设置为 NIL? NIL 是否应该首先创建一个单独的单例类,然后在树定义中使用?我现在分配给 T.NIL (cmets) 时遇到错误

#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;
} 

【问题讨论】:

    标签: c++ red-black-tree


    【解决方案1】:

    您需要在代码中将Node::Node() 的主体进一步向下移动;在 class Tree 之后的任何地方定义(在你拥有它的时候,Tree 只被声明了)。

    【讨论】:

      猜你喜欢
      • 2020-12-02
      • 2018-06-17
      • 2014-09-23
      • 2011-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-30
      • 2021-03-20
      相关资源
      最近更新 更多