我試圖實現紅黑樹數據結構,並遇到來自Apple Open Source項目的this示例。這是創建樹的代碼:我想知道什麼是具有前哨淋巴結而不是孩子指着NULL
背後的推理爲什麼紅黑樹中的自引用標記比檢查NULL更簡單?
/*
* 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);
}
。無論如何我們必須按照我的理解來檢查。
另外我不明白爲什麼我們需要假根,以及根在理論上如何分裂?
如果我沒有記錯,一個常見的技巧是將「rb-flag」放入一個通常爲0的子指針的最小位(由於字對齊的地址)。這節省了每個節點的一個字節甚至一個字。在這種情況下,與0進行比較可能不得不掩蓋這一點 - 與自身比較沒有。但是,這只是猜測...... – Scheff
@Scheff:這可能是,但這裏引用的代碼似乎會存儲一個單獨的顏色成員。 – doynax
對不起,我甚至沒有讀過代碼 - 我的錯...... – Scheff