算法导论-红黑树C++实现
红黑树的定义:
一棵二叉查找树如果满足下面的红黑性质,则为一棵红黑树:
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
相关推荐
duyifei0 2019-06-21
luadenis0 2020-06-10
Bloddy 2020-06-08
码墨 2020-05-29
tlsmile 2020-05-20
李高峰 2020-05-03
lickylin 2020-04-22
xhao 2020-03-05
翡翠谷 2020-01-28
蜗牛慢爬的李成广 2020-01-19
mbcsdn 2020-01-07
waitwolf 2020-01-01
hanyujianke 2020-01-01
zhujiangtaotaise 2019-12-22
大黑 2019-11-05
frommymind 2019-08-30
齐天大圣数据候 2019-11-02
了不起的厂长 2019-07-01
AreayGK 2019-07-01