数据结构之
基于不同策略的英文单词的词频统计和检索系统
本次更新了基于二叉排序树的相关代码,此代码为独立运行测试代码。
用于构建存放单词的二叉排序树,并且可以查找单词,中序遍历输出二叉排序树。
整个系统已全部更新完成,在专栏里有。
#include <iostream>
using namespace std;
//词频结构
struct word_frequency
{
string word;
int frequency;
}linelist_word_fre[10];
typedef word_frequency datatype;//元素类型
struct BiNode
{
datatype data;
BiNode* lchild, * rchild;
};
class BiSortTree
{
public:
BiSortTree(datatype a[], int n); //构造函数
~BiSortTree() { Release(root); } //析构函数
void InOrder() { InOrder(root); } //中序遍历二叉树
BiNode* InsertBST(datatype x) { return InsertBST(root, x); } //插入记录x
BiNode* SearchBST(string k) { return SearchBST(root, k); } //查找值为k的结点
private:
void Release(BiNode* bt);
BiNode* InsertBST(BiNode * bt, datatype x);
BiNode * SearchBST(BiNode * bt, string k);
void InOrder(BiNode * bt); //中序遍历函数调用
BiNode * root; //二叉排序树的根指针
};
void BiSortTree::InOrder(BiNode * bt)
{
if (bt == nullptr) return; //递归调用的结束条件
else
{
InOrder(bt->lchild); //前序递归遍历bt的左子树
cout << bt->data.word << endl; //访问根结点bt的数据域
InOrder(bt->rchild); //前序递归遍历bt的右子树
}
}
BiNode * BiSortTree::SearchBST(BiNode * bt, string k)
{
if (bt == nullptr) return nullptr;
if (bt->data.word == k) return bt;
else if (bt->data.word > k) return SearchBST(bt->lchild, k);
else return SearchBST(bt->rchild, k);
}
BiNode * BiSortTree::InsertBST(BiNode * bt, datatype x)
{
if (bt == nullptr)//找到插入位置
{
BiNode * s = new BiNode ;
s->data = x;
s->lchild = nullptr;
s->rchild = nullptr;
bt = s;
return bt;
}
else if (bt->data.word > x.word)
{
bt->lchild = InsertBST(bt->lchild, x);
return bt;
}
else
{
bt->rchild = InsertBST(bt->rchild, x);
return bt;
}
}
//构造函数
BiSortTree::BiSortTree(datatype a[], int n)
{
root = nullptr;
for (int i = 0; i < n; i++)
root = InsertBST(root, a[i]);
}
//析构函数
void BiSortTree::Release(BiNode * bt)
{
if (bt == nullptr) return;
else {
Release(bt->lchild); //释放左子树
Release(bt->rchild); //释放右子树
delete bt; //释放根结点
}
}
int main()
{
BiNode * p = nullptr;
linelist_word_fre[0].frequency = 1;
linelist_word_fre[1].frequency = 2;
linelist_word_fre[2].frequency = 3;
linelist_word_fre[0].word = "ling";
linelist_word_fre[1].word = "yu";
linelist_word_fre[2].word = "优快云";
BiSortTree B(linelist_word_fre,3);
B.InOrder();
string key;
cout << "请输入查找的元素值"<<endl;
cin >> key;
p = B.SearchBST(key);
if (p != nullptr)
cout << p->data.word << " " <<p->data.frequency<< endl;
else
cout << "查找失败" << endl;
system("pause");
return 0;
}
如有问题请在评论区留言,一起交流进步。