简体   繁体   English

为什么红黑树中的自引用标记比检查NULL更简单?

[英]Why a self-referencing sentinel in a red-black tree is simpler than having to check for NULL?

I'm trying to implement red-black tree data structure and came across this example from Apple Open Source project. 我正在尝试实现红黑树数据结构,并从Apple Open Source项目中看到了这个例子。 This is the code for creating a tree: 这是创建树的代码:

/*
 * Create a red black tree struct using the specified compare routine.
 * Allocates and returns the initialized (empty) tree.
 */
struct rbtree *
rbcreate(compar)
    int (*compar)__P((const void *, const void*));
{
    struct rbtree *tree;

    tree = (struct rbtree *) emalloc(sizeof(*tree));
    tree->compar = compar;

    /*
     * We use a self-referencing sentinel node called nil to simplify the
     * code by avoiding the need to check for NULL pointers.
     */
    tree->nil.left = tree->nil.right = tree->nil.parent = &tree->nil;
    tree->nil.color = black;
    tree->nil.data = NULL;

    /*
     * Similarly, the fake root node keeps us from having to worry
     * about splitting the root.
     */
    tree->root.left = tree->root.right = tree->root.parent = &tree->nil;
    tree->root.color = black;
    tree->root.data = NULL;

    return(tree);
}

I'm wondering what is the reasoning behind having the sentinel node instead having the children pointing to NULL . 我想知道使用sentinel节点而不是让子节点指向NULL In any case we have to check as far as I understand. 无论如何,据我所知,我们必须检查。

Also I don't understand why we need fake root and how the root can even be split in theory? 另外,我不明白为什么我们需要假根以及根本如何在理论上分裂?

Let's say you want to check one of the main properties of the RB tree, that there are no adjacent red nodes. 假设您要检查RB树的一个主要属性,即没有相邻的红色节点。

With NULL representation, it looks like this: 使用NULL表示,它看起来像这样:

node->color == black || (node->left == NULL || node->left->color == black) && (node->right == NULL || node->right->color == black)

Sentinel representation allows to express it more concisely: Sentinel表示允许更简洁地表达它:

node->color == black || node->left->color == black && node->right->color == black

Same simplification applies to the actual checks in the tree operations. 相同的简化适用于树操作中的实际检查。

Similar story with the fake root. 与假根相似的故事。 It ensures that the tree is never empty, and thus eliminates a special case from the tree insertion routine. 它确保树永远不会为空,从而消除树插入例程中的特殊情况。 (No idea what they meant by spitting though.) (不知道吐痰意味着什么。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM