一、实验目的
- 理解动态查找表和二叉排序树的概念;
- 掌握二叉排序树的构造算法及其实现方法;
- 掌握二叉排序树的查找算法及其实现方法;
- 二叉排序树中的记录和待查找的关键字值要从终端输入,输入的记录格式为(整数,序号),例如(3,2)表示关键字值为3,输入序号为2的记录;
- 算法要具有较好的健壮性,对错误操作要做适当处理。
二、实验任务
- 输入一组记录构造一棵二叉排序树,并且输出这棵二叉排序树的中序序列;
- 给定一个关键字值,对所构造的二叉排序树进行查找,并输出查找的结果。
三、实验过程与结果
#include"stdafx.h"
#include<iostream>
#include<string>
using namespace std;
template<typename keytype,typename type>
struct TableElemType {
keytype key;
type value;
};
template<typename keytype, typename type>
struct BSTNode {
TableElemType<keytype, type> data;
BSTNode<keytype,type>* LChild;
BSTNode<keytype,type>* RChild;
};
template<typename keytype, typename type>
class BSTree {
private:
BSTNode<keytype,type>* T;
public:
void createBST() {
TableElemType<keytype,type> e;
BSTNode<keytype, type>* q;
T = q = NULL;
keytype key;
type value;
cout << "输入关键字和值:";
cin >> key >> value;
e.key = key;
e.value = value;
while (key!=-1) {
if (!searchBST(key, q))
insertBST(e);
cout << "输入关键字和值:";
cin >> key >> value;
e.key = key;
e.value = value;
}
}
void insertBST(TableElemType<keytype, type> e) {
BSTNode<keytype, type>* p, * q;
if (T == NULL) {
p = new BSTNode<keytype, type>;
p->data = e;
p->LChild = p->RChild = NULL;
T = p;
}
else {
if (!searchBST(e.key, q)) {
p = new BSTNode<keytype, type>;
p->data = e;
p->LChild = p->RChild = NULL;
if (e.key < q->data.key)
q->LChild = p;
else
q->RChild = p;
}
}
}
bool searchBST(keytype k, BSTNode<keytype, type>*& q) {
BSTNode<keytype, type>* p, * f;
p = T;
q = f = NULL;
if (p == NULL) {
return false;
}
while (p) {
if (k == p->data.key) {
q = p;
return true;
}
else if (k<p->data.key) {
f = p;
p = p->LChild;
}
else {
f = p;
p = p->RChild;
}
}
q = f;
return false;
}
void show(){
cout << "\n其中序遍历序列为:" << endl;
inOrderTraver(T);
}
void inOrderTraver(BSTNode<keytype, type>* t) {
if (t) {
inOrderTraver(t->LChild);
cout << t->data.key << "-->" << t->data.value << endl;
inOrderTraver(t->RChild);
}
}
};
int main() {
BSTree<int, string> T;
T.createBST();
T.show();
cout << "输入要查找的关键字:";
int key;
BSTNode<int, string>* q;
cin >> key;
if (!T.searchBST(key, q)) {
if (q == NULL)
cout << "空树,无法找到关键字!";
else
cout<< "没有此关键字!";
}
else {
cout << "找到该关键字(" << q->data.key << ")对应的值为:" << q->data.value << endl;
}
return 0;
}