1)二叉搜索树的基本操作实现
a)函数的声明和结构体的定义
#include <iostream>
#include <stdlib.h>
using namespace std;
struct BSTsearch{
string name;
BSTsearch *left, *right;
};
void error(string msg);
void insertNode(BSTsearch * &t, string key);
BSTsearch * findNode(BSTsearch * t, string key);
void showNode(BSTsearch * t);
void removeNode(BSTsearch * &root,BSTsearch * t, string key);
BSTsearch * findRight(BSTsearch * t);
BSTsearch * findLeft(BSTsearch * t);
BSTsearch * & findPointer(BSTsearch * & t, string key);
b)主函数(主要是检验一下函数的正确性)
int main()
{
BSTsearch * t = NULL;
insertNode(t, "Grumpy");
insertNode(t, "Sleepy");
insertNode(t, "Doc");
insertNode(t, "Bashful");
insertNode(t, "Dopey");
insertNode(t, "Happy");
insertNode(t, "Sneezy");
showNode(t);
removeNode(t, t, "Sneezy");
cout << endl;
showNode(t);
return 0;
}
c)二叉搜索树插入一个Node的实现(递归)
//加&是由于插入过程会修改二叉搜索树的指针的内容
void insertNode(BSTsearch * &t, string key){
if (t == NULL){
t = (BSTsearch *)malloc(sizeof(BSTsearch));
t->name = key;
t->left = t->right = NULL;
}
else{
if (t->name != key){
if (key > t->name){
insertNode(t->right, key);
}
else{
insertNode(t->left, key);
}
}
}
}
d)二叉搜索树查询
//输入一个二叉搜索树和key,然后返回一个指针
BSTsearch * findNode(BSTsearch *t, string key){
if (t == NULL){
return NULL;
}
if (t->name == key){
return t;
}
if (t->name < key){
return findNode(t->right, key);}
else{
return findNode(t->left, key);}
}
e)二叉搜索树的遍历(中序遍历)
void showNode(BSTsearch *t){
if (t == NULL)
return;
showNode(t->left);
cout << t->name << endl;
showNode(t->right);
}
f)二叉搜索树的移除(这个感觉麻烦一点)
void removeNode(BSTsearch * &root, BSTsearch *t, string key){
if (t == NULL){
return;
}
else if (t->name == key){
if (t->left != NULL){
BSTsearch * right = findRight(t->left);
string tem = right->name;
BSTsearch * test = findNode(t->left, tem);
findPointer(root, tem) = NULL;
free(test);
t->name = tem;
}
else if (t->right != NULL){
BSTsearch * left = findLeft(t->right);
string tem = left->name;
BSTsearch * test = findNode(t->right, tem);
findPointer(root, tem) = NULL;
free(test);
t->name = tem;
}
else{
string tem = t->name;
BSTsearch * test = findNode(root, tem);
findPointer(root, tem) = NULL;
free(test);
}
}
else if (t->name < key){
removeNode(root, t->right, key);
}
else{
removeNode(root, t->left, key);
}
}
g)返回一个节点最左边的孩子节点
BSTsearch * findLeft(BSTsearch *t){
if (t == NULL)
return NULL;
else{
while(t->left != NULL){
t = t->left;
}
return t;
}
}
h)返回一个节点最右边的孩子节点
BSTsearch * findRight(BSTsearch *t){
if (t == NULL)
return NULL;
else{
while(t->right != NULL){
t = t->right;
}
return t;
}
}
i)返回key的节点
BSTsearch * &findPointer(BSTsearch * &t, string key){
if (t == NULL){
error("there is no element.");
}
else if (t->name == key)
return t;
else if (t->name < key)
return findPointer(t->right, key);
else
return findPointer(t->left, key);
}
j)报错函数
void error(string msg){
cerr << msg;
exit(EXIT_FAILURE);
}