AVL树的删除
来源:互联网 发布:网络研修日志 编辑:程序博客网 时间:2024/06/13 03:13
AVL数的删除前面的操作和二叉搜索树的删除操作相同,只是在删除时顺便修改pParent的平衡因子,在删除完后,根据pParent的平衡因子,向上调整平衡因子直到平衡。
当pParent->_bf == 0时,需要向上调整;
当pParent->_bf == 1时,不需要修改,直接退出即可;
当pParent->_bf == 2时,需要进行左旋或右旋。
bool Destory(const K& key) { if(_pRoot == NULL) { return false; } if(_pRoot->_key == key && _pRoot->_pLeft == NULL \ && _pRoot->_pRight == NULL) { delete _pRoot; _pRoot = NULL; return true; } else { Node* pCur = _pRoot; Node* pParent = NULL; while(pCur) { //先找到要删除的位置 if(pCur->_key > key) { pParent = pCur; pCur = pCur->_pLeft; } else if(pCur->_key < key) { pParent = pCur; pCur = pCur->_pRight; } else break; } if(pCur) { if(pCur->_pLeft == NULL) { if(pCur != _pRoot) { if(pParent->_pLeft == pCur) { pParent->_pLeft = pCur->_pRight; pParent->_bf++; } else { pParent->_pRight = pCur->_pRight; pParent->_bf--; } } else { _pRoot = pCur->_pRight; _pRoot->_bf--; } } else if(pCur->_pRight == NULL) { if(pCur != _pRoot) { if(pParent->_pLeft == pCur) { pParent->_pLeft = pCur->_pLeft; pParent->_bf++; } else { pParent->_pRight = pCur->_pLeft; pParent->_bf--; } } else { _pRoot = pCur->_pLeft; _pRoot->_bf++; } } else { pParent = pCur; Node* firstNode = pCur->_pRight; while(firstNode->_pLeft) { pParent = firstNode; firstNode = firstNode->_pLeft; } pCur->_bf = firstNode->_bf; pCur->_key = firstNode->_key; pCur->_value = firstNode->_value; if(firstNode == pParent->_pLeft) { pParent->_pLeft = firstNode->_pRight; pParent->_bf++; } else { pParent->_pRight = firstNode->_pRight; pParent->_bf--; } pCur = firstNode; } } //调整 while(pParent) { //如果双亲的平衡因子是1或-1,说明该子树高度不变 if(abs(pParent->_bf) == 1) return true; //如果双亲的平衡因子是0,需要向上调整 else if(pParent->_bf == 0) { pCur = pParent; pParent = pParent->_pParent; } //此时的平衡因子是2或-2,需要进行旋转减小平衡因子 else { //右子树较高 if(pParent->_bf == 2) { _RotateL(pParent); } else { _RotateR(pParent); } break; } if(pCur == pParent->_pLeft) pParent->_bf++; else pParent->_bf--; } delete pCur; pCur = NULL; } return true; }
注:其他代码参考前一篇博客。
阅读全文
0 0
- AVL树的删除
- AVL树的删除探讨
- 算法--AVL树的删除
- AVL树的插入删除分析
- AVL树的插入、删除、旋转
- AVL树的查找,插入,删除
- AVL树的插入与删除
- AVL树的插入、删除、旋转
- AVL树的插入和删除
- AVL树删除算法的实现
- AVL树的旋转,插入,删除操作
- AVL 树的插入和删除
- avl树的插入与删除
- AVL树的插入删除操作
- AVL树的插入与删除
- AVL树的插入与删除操作
- 数据结构-----AVL树的插入删除操作
- AVL树的插入、删除、查找操作
- 函数的公有属性和私有属性
- .NET内置特性(一)
- Java简单操作Properties配置文件(实例详解)
- hive原理与源码分析-ACID及总结(八)
- 用python写登陆界面
- AVL树的删除
- Filter | 日志处理 | 应用例子
- 接口和抽象类有什么区别
- 自定义-MVC
- 浅谈程序开发中的编程思想
- 【机器学习】人工神经网络(ANN)浅讲
- HTML代码的缩写
- DNS协议简述
- python生成器详解