其实这是实验课的作业,写起来才发现学了两个月数据结构写树都不流畅——不过代码量还是挺大的。
【注意,以下的代码是跑不了的】
这里只是个框架,我添加了很多注释,希望能够方便大家启迪思路;作业的话还是多查查资料,自己动手吧。
#include<iostream>
#include<string>
using namespace std;
class node {
public:
string cityName;
int x;
int y;
node* left;
node* right;
node(string name, int cx, int cy) {
cityName = name;
x= cx;
y = cy;
left = NULL;
right = NULL;
}
};
class BST {
private:
int numNode;
node* root;
public:
BST() {
numNode = 0;
root = NULL;
}
//
void insert(string cName, int cx, int cy) {//插入结点
root = insert(root, cName, cx, cy);
};
node* insert(node* nd, string cName, int cx, int cy) {
//走到底了就新建一个结点
//假定城市不重名
//不然和当前结点比较,看看是该放在左侧的树上还是放在右侧的树上
}
///
void deleteNode(string cName) {//删除结点及配套函数
if (root == NULL) {
cout << "EMPTY TREE ERROT" << endl;
return;
}
else {
deleteNode(root, cName);
}
};
void deleteNode(node*& nd, string cName) {
//如果走到底还没找到要删除的,那么就提示找不到吧
//和当前结点比较,看看应该去左边找还是去右边找
if (cName < nd->cityName) {
}
else if (cName > nd->cityName) {
}
else {//找到了
//讨论这个要删的结点拥有的子树的情况
//分只有左,只有右,都没有,左右双全
}
}
//删除左右双全结点需要用到的函数
void findMin() {
}
node* findMin(node* nd) {
}
node* deleteMin(node* nd) {
//删掉根节点为nd的树的最小结点
//注意这个最小结点可能有右子树,所以需要考虑连接。
}
///
void search(string cName) {//检索指定城市
if (root == NULL) {
cout << "EMPTY TREE ERROR" << endl;
return;
}
else {
search(root, cName);
}
}
void search(node* nd, string cName) {
//检索的操作非常像插入!
};
void inOrder() {//中序输出
inOrder(root);
}
void inOrder(node* nd) {
if (nd == NULL) return;
inOrder(nd->left);
cout << nd->cityName << endl;
inOrder(nd->right);
}
/
void displayStartwith(char prefix) {//展示指定字母打头所有城市
displayStartwith(root, prefix);
}
void displayStartwith(node* nd, char prefix) {
//我用了中序遍历,但我觉得会有更好的办法
}
/
void displayCloserThan(int tx, int ty, int len) {//检索距离范围
displayCloserThan(root, tx, ty, len);
}
void displayCloserThan(node* nd, int tx, int ty, int len) {
//也是基于中序遍历
};
//控制for循环的参数
int m, n, k, j, h;
//城市数,删除数,检索数,检索开头数,检索范围数
int main() {
BST bt;
cin >> m >> n >> k >> j >> h;
//输入城市数据
for (int i = 0; i < m; i++) {
}
//输入要删除的城市
for (int i = 0; i < n; i++) {
}
//输入要检索的城市
for (int i = 0; i < k; i++) {
}
//输入要检索的打头字母
for (int i = 0; i < j; i++) {
}
//输入给定坐标及距离范围
for (int i = 0; i < h; i++) {
}
return 0;
}