红黑树
来源:互联网 发布:java 请求分发算法 编辑:程序博客网 时间:2024/05/29 11:17
const bool RED = true;const bool BLACK = false;struct Node{ int num; Node* left; Node* right; bool color; int N; Node(int v) { num = v; left = right = NULL; color = RED; N = 1; }};class RBTree{public: RBTree() { root = NULL; } void AddNode(int v) { root = AddNode(root,v); } int Rank(int v) { return Rank(root,v); } int RangeSearch(int lo,int hi) { cnt = 0; RangeSearch(root,lo,hi); return cnt; } void print() { print(root); }private: Node* root; int cnt; Node* AddNode(Node* x,int v) { if (x == NULL) return new Node(v); int cmp = x->num - v; if(cmp>0) x->left = AddNode(x->left,v); else if(cmp<0) x->right = AddNode(x->right,v); else x->num = v; if(isRed(x->right)&&!isRed(x->left)) x = rotateLeft(x); if(isRed(x->left)&&isRed(x->left->left)) x = rotateRight(x); if(isRed(x->left)&&isRed(x->right)) flipColors(x); x->N = Size(x->left) + Size(x->right) + 1; return x; } int Rank(Node* x,int v) { if(x == NULL) return 0; int cmp = x->num - v; if(cmp>0) return Rank(x->left,v); else if (cmp<0) 1+ Size(x->left) + Rank(x->right,v); else return Size(x->left); } void RangeSearch(Node* x,int lo,int hi) { if(x == NULL ) return; int cmplo = lo - x->num; int cmphi = hi - x->num; if(cmplo>0) RangeSearch(x->right,lo,hi); if(cmplo<=0&&cmphi>=0) { cnt++; RangeSearch(x->left,lo,hi); RangeSearch(x->right,lo,hi); } if(cmphi<0) RangeSearch(x->left,lo,hi); } void print(Node*x) { if(x == NULL ) return ; print(x->left); cout<<" "<<x->num<<" "; print(x->right); } Node* rotateLeft(Node* h) { Node* x = h->right; h->right = x->left; x->left = h; x->color = h->color; h->color = RED; return x; } Node* rotateRight(Node* h) { Node* x = h->left; h->left = x->right; x->right = h; x->color = h->color; h->color = RED; return x; } Node* flipColors(Node* h) { h->left->color = BLACK; h->right->color = BLACK; h->color = RED; } bool isRed(Node* x) { if(x == NULL) return false; return x->color == RED; } int Size(Node* x) { if(x == NULL) return 0; else return x->N; }};
0 0
- 红黑树
- 红黑树
- 红黑树
- 红黑树
- 红黑树
- 红黑树
- 红黑树
- 红黑树
- 红黑树
- 红黑树
- 红黑树
- 红黑树
- 红黑树
- 红黑树
- 红黑树
- 红黑树
- 红黑树
- 红黑树
- 错误码:2003 不能连接到mysql服务器
- html base64 img 图片显示
- Drozer – Android APP安全评估工具(附测试案例)
- Attempting to badge the application icon but haven't received permission解决方案
- MySQL语法大全
- 红黑树
- 简单的数据库交互展示
- java连接mysql
- Struts2 ValueStack
- cocos2dx画扇形
- 降维工具箱
- Cloud Foundry 部署问题(2)buildpack时间过长
- Spring MVC 简单demo1
- 个人面试题(oracle数据库开发)(一)