AVL树
来源:互联网 发布:照片叠加软件 编辑:程序博客网 时间:2024/06/05 04:02
AVL树相比较红黑树而言,是一种更加严格的平衡树,在插入和删除的时候,需要通过旋转来实现平衡。具体实现比红黑树简单。
代码:
#include<iostream>using namespace std;struct TNode{ int value; int h; TNode * left; TNode * right; TNode * parent; TNode() { left = NULL; right = NULL; parent = NULL; h = 1; }};struct Tree{ TNode * root; Tree() { root = NULL; }};void avl_insert(Tree & t,int value);void avl_fixup(Tree&t,TNode *x);int tnodeh(TNode *x);void refreshnode(Tree&t,TNode *x);int mymax (int a,int b);void left_rotate(Tree&t,TNode*x);void right_rotate(Tree&t,TNode*x);void printT(TNode *x);void avl_delete(Tree &t,TNode*x);void tp(int i){// cout << i << endl;}int main (){ Tree t; for (int i = 1; i < 5;i ++) { avl_insert(t,i); } for (int i = 10; i > 6;i --) { avl_insert(t,i); } printT(t.root);}void avl_insert(Tree&t,int value){ TNode * p = t.root; TNode * q = NULL; TNode * s = new TNode(); s->value = value; if (NULL == t.root) { t.root = s; } else { while (p != NULL) { q = p; if (p->value < value) { p = p->right; } else { p = p->left; } } if (q->value < value) { q->right = s; } else { q->left = s; } s->parent = q; avl_fixup(t,s); }}void avl_fixup(Tree&t,TNode *x){ TNode * p = x->parent; while (p!= NULL) { refreshnode(t,p); p = p->parent; }}int tnodeh(TNode *x){ int h = 0; if (NULL != x) { h = x->h; } return h;}void refreshnode(Tree&t,TNode *x){ int lh = tnodeh(x->left); int rh = tnodeh(x->right); int tmp = lh-rh; tp(1); if (tmp> 2) { tp(2); right_rotate(t,x); refreshnode(t,x); // refreshnode(t,x->parent); } else if (tmp < -2) { tp(3); left_rotate(t,x); refreshnode(t,x); // refreshnode(t,x->parent); } else { x->h = mymax(lh,rh)+1; }}int mymax(int a,int b){ return a>b?a:b;}void left_rotate(Tree&t,TNode*x){ tp(10); TNode * y =x->right; if (t.root == x) { t.root = y; } else if (x->parent->left == x) { x->parent->left = y; } else { x->parent->right = y; } y->parent = x->parent; x->right = y->left; if ( NULL != x->right) { x->right->parent = x; } x->parent = y; y->left = x; tp(10);}void right_rotate(Tree&t,TNode*x){ TNode * y =x->left; if (t.root == x) { t.root = y; } else if (x->parent->left == x) { x->parent->left = y; } else { x->parent->right = y; } y->parent = x->parent; x->left = y->right; if ( NULL != x->left) { x->left->parent = x; } x->parent = y; y->right = x;}void printT(TNode *x){ if (x != NULL) { cout << x->value << " "<< x->h << endl; printT(x->left); printT(x->right); }}void avl_delete(Tree &t,TNode*x){}
0 0
- AVL树
- AVL树
- AVL树
- avl树
- AVL树
- avl树
- AVL树
- AVL树
- AVL树
- AVL树
- avl树
- avl树
- AVL树
- AVL树
- AVL树
- AVL树
- AVL 树
- AVL树
- redis info 参数说明
- 字符串表现形式区别
- 实现备份与还原,需用到的方法
- 刚刚结束的Java三次面试
- 获取时间
- AVL树
- 笔记32--目录values下xml文件:TypeArray、attrs、styles、colors、strings、dimens
- Struts2的工作原理
- 再论代码生成器
- mysql 表锁演示
- ZOJ 3498 Javabeans (二分)
- Oracle corrupt block(坏块) 详解
- DB2数据库内存耗尽故障处理经验分享
- OSGI服务总结