通过二叉树存单词,并且对总共的单词数量进行计数,二叉树自适应的将出现频率高的单词往上移动以减少二叉树的搜索时间。
代码如下
/***********************genSplay.h***********************/
#ifndef _GENSPLAY_H_
#define _GENSPLAY_H_
#include <iostream>
using namespace std;
//树节点
template<class T>
class SplayingNode
{
public:
T info;
SplayingNode *left, *right, *parent; //节点指针
SplayingNode(){
left = right = parent = 0;
}
SplayingNode(const T &el, SplayingNode *l = 0,
SplayingNode *r = 0, SplayingNode *p = 0)
:info(el), left(l), right(r), parent(p){ }
};
//二叉树
template<class T>
class SplayTree
{
protected:
SplayingNode<T> *root;
void rotateR(SplayingNode<T> *); //向右旋转
void rotateL(SplayingNode<T> *); //向左旋转
void continueRotation(SplayingNode<T> *gr, SplayingNode<T> *par,
SplayingNode<T> *ch, SplayingNode<T> *desc); //重新定义父节点指针
void semisplay(SplayingNode<T> *); //更改树结构,将权值大的向上移动
void inorder(SplayingNode<T> *); //中序遍历
void virtual visit(SplayingNode<T> *){ } //虚函数
public:
SplayTree(){
root = 0;
}
void inorder(){
inorder(root);
}
T *search(const T &);
void insert(const T &);
};
template<class T>
void SplayTree<