紅黑樹的定義:
一棵二叉查找樹如果滿足下面的紅黑性質,則為一棵紅黑樹:
1)每個節點或是紅的,或是黑的。
2)根節點是黑的。
3)每個葉節點(NIL)是黑節點。
4)如果一個節點是紅的,則它的兩個兒子都是黑的。
5)對每個節點,從該節點到其子孫節點的所有路徑上包含相同節點數目的黑節點。
C++代碼實現:
BRTreeNode.h
- #ifndef BRTREENODE_H_INCLUDED
- #define BRTREENODE_H_INCLUDED
- #include<iostream>
- usingnamespace std;
- class BRTree;
- class BRTreeNode
- {
- private:
- friendclass BRTree;
- int key;
- bool color;
- BRTreeNode* left;
- BRTreeNode* right;
- BRTreeNode* parent;
- public:
- BRTreeNode():key(-1),color(0),left(NULL),right(NULL),parent(NULL){}
- BRTreeNode(BRTreeNode* node):key(node->key),color(node->color),left(node->left),right(node->right),parent(node->parent)
- {}
- BRTreeNode(int num,bool flag):key(num),color(flag),left(NULL),right(NULL),parent(NULL){}
- ~BRTreeNode()
- {
- }
- int Getkey()
- {
- return key;
- }
- bool Getcolor()
- {
- returnthis->color;
- }
- BRTreeNode* GetLeft()
- {
- returnthis->left;
- }
- BRTreeNode* Getright()
- {
- returnthis->right;
- }
- BRTreeNode* Getparent()
- {
- returnthis->parent;
- }
- void Inorder()
- {
- if(this!=NULL)
- {
- this->left->Inorder();
- cout<<this->key<<" ";
- this->right->Inorder();
- }
- }
- void Preorder()
- {
- if(this!=NULL)
- {
- cout<<this->key<<" ";
- this->left->Preorder();
- this->right->Preorder();
- }
- }
- void Postorder()
- {
- if(this!=NULL)
- {
- this->left->Postorder();
- this->right->Postorder();
- cout<<this->key<<" ";
- }
- }
- void MakeEmpty()
- {
- if(this!=NULL)
- {
- this->left->MakeEmpty();
- this->right->MakeEmpty();
- deletethis;
- }
- }
- int GetHeight()
- {
- int L,R;
- if(this==NULL)
- {
- return 0;
- }
- L=this->left->GetHeight();
- R=this->right->GetHeight();
- return 1+(L>R? L:R);
- }
- };
- #endif // BRTREENODE_H_INCLUDED