图书管理系统 二叉树 代码 复杂一点
时间: 2024-06-19 18:01:39 浏览: 100
图书管理系统可以通过二叉树来实现,具体的实现方式包括以下几个步骤:
1. 定义一个书籍结构体,包括书名、作者、出版日期、价格等信息;
2. 定义一个二叉树节点结构体,包括书籍结构体指针、左子树指针和右子树指针;
3. 定义一个二叉树类,包括插入节点、删除节点、查找节点等操作;
4. 在插入节点时,可以按照书籍的某个属性(例如书名或者价格)来比较大小,以保证二叉树的有序性;
5. 在删除节点时,需要考虑三种情况:删除叶子节点、删除只有一个子节点的节点、删除有两个子节点的节点。对于有两个子节点的节点,可以选择将其右子树中最小的节点替换到该节点的位置上,从而保证二叉树的有序性不变。
这是一个简单的二叉树实现图书管理系统的思路,具体的代码实现可以参考以下示例:
```
#include <iostream>
using namespace std;
struct Book {
string name;
string author;
string date;
double price;
};
struct TreeNode {
Book* book;
TreeNode* left;
TreeNode* right;
};
class BookTree {
public:
BookTree() {
root = NULL;
}
void insert(Book* book) {
TreeNode* node = new TreeNode();
node->book = book;
node->left = NULL;
node->right = NULL;
if (root == NULL) {
root = node;
return;
}
TreeNode* p = root;
while (true) {
if (book->name < p->book->name) {
if (p->left == NULL) {
p->left = node;
break;
} else {
p = p->left;
}
} else {
if (p->right == NULL) {
p->right = node;
break;
} else {
p = p->right;
}
}
}
}
void remove(string name) {
TreeNode* p = root;
TreeNode* parent = NULL;
while (p != NULL && p->book->name != name) {
parent = p;
if (name < p->book->name) {
p = p->left;
} else {
p = p->right;
}
}
if (p == NULL) {
return;
}
if (p->left == NULL && p->right == NULL) {
if (parent == NULL) {
root = NULL;
} else if (parent->left == p) {
parent->left = NULL;
} else {
parent->right = NULL;
}
delete p->book;
delete p;
} else if (p->left != NULL && p->right == NULL) {
if (parent == NULL) {
root = p->left;
} else if (parent->left == p) {
parent->left = p->left;
} else {
parent->right = p->left;
}
delete p->book;
delete p;
} else if (p->left == NULL && p->right != NULL) {
if (parent == NULL) {
root = p->right;
} else if (parent->left == p) {
parent->left = p->right;
} else {
parent->right = p->right;
}
delete p->book;
delete p;
} else {
TreeNode* q = p->right;
TreeNode* q_parent = p;
while (q->left != NULL) {
q_parent = q;
q = q->left;
}
if (q_parent == p) {
q->left = p->left;
if (parent == NULL) {
root = q;
} else if (parent->left == p) {
parent->left = q;
} else {
parent->right = q;
}
delete p->book;
delete p;
} else {
q_parent->left = q->right;
q->left = p->left;
q->right = p->right;
if (parent == NULL) {
root = q;
} else if (parent->left == p) {
parent->left = q;
} else {
parent->right = q;
}
delete p->book;
delete p;
}
}
}
Book* search(string name) {
TreeNode* p = root;
while (p != NULL && p->book->name != name) {
if (name < p->book->name) {
p = p->left;
} else {
p = p->right;
}
}
if (p == NULL) {
return NULL;
} else {
return p->book;
}
}
private:
TreeNode* root;
};
```
阅读全文