目录
1. 头文件
需要引入C++ 数据结构学习 ---- 二叉搜索树_孤城寻欢的博客-CSDN博客的二叉搜索树文件
#include"BST.h"
template <typename T> class Splay : public BST<T> { //由BST派生的Splay树模板类
protected:
BinNodePosi(T) splay(BinNodePosi(T) v); //将节点v伸展至根
public:
BinNodePosi(T)& search(const T& e); //查找(重写)
BinNodePosi(T) insert(const T& e); //插入(重写)
bool remove(const T& e); //删除(重写)
};
//在节点*p与*lc(可能为空)之间建立父(左)子关系
template <typename NodePosi> inline void attachAsLC(NodePosi lc, NodePosi p) { p->lc = lc; if (lc) lc->parent = p; }
//在节点*p与*rc(可能为空)之间建立父(右)子关系
template <typename NodePosi> inline void attachAsRC(NodePosi p, NodePosi rc) { p->rc = rc; if (rc) rc->parent = p; }
2. 相关函数
2.1 插入函数
//将关键码e插入伸展树中
template <typename T> BinNodePosi(T) Splay<T>::insert(const T& e) {
if (BST<T>::_root==NULL) { this->_size = 1; return this->_root = new BinNode<T>(e); } //原树为空
BinNodePosi(T) t = search(e); if (e == t->data) return t; //目标节点t若存在,伸展至根
if (t->data < e) { //在右侧嫁接
t->parent = this->_root = new BinNode<T>(e, NULL, t, t->rc); //lc == t必非空
if (t->rc) { t->rc->parent = this->_root; t->rc = NULL; } //rc或为空
}
else { //在左侧嫁接
t->parent = this->_root = new BinNo