c++家谱管理系统二叉树
时间: 2023-10-03 09:08:28 浏览: 110
二叉树是一种常用的数据结构,我们可以通过二叉树来实现家谱管理系统。下面是一个简单的C++代码示例:
```c++
#include <iostream>
#include <string>
using namespace std;
// 家谱节点
struct Genealogy {
string name; // 姓名
Genealogy *father; // 父亲节点指针
Genealogy *mother; // 母亲节点指针
Genealogy(string n) : name(n), father(NULL), mother(NULL) {}
};
// 二叉树节点
struct TreeNode {
Genealogy *data; // 数据
TreeNode *left; // 左子节点指针
TreeNode *right; // 右子节点指针
TreeNode(Genealogy *d) : data(d), left(NULL), right(NULL) {}
};
// 插入节点
void insert(TreeNode *&root, Genealogy *data) {
if (root == NULL) {
root = new TreeNode(data);
return;
}
if (data->name < root->data->name) {
insert(root->left, data);
} else if (data->name > root->data->name) {
insert(root->right, data);
}
}
// 查找节点
Genealogy *search(TreeNode *root, string name) {
if (root == NULL) {
return NULL;
}
if (root->data->name == name) {
return root->data;
} else if (name < root->data->name) {
return search(root->left, name);
} else {
return search(root->right, name);
}
}
// 打印家谱
void print(Genealogy *root, int level) {
if (root == NULL) {
return;
}
for (int i = 0; i < level; i++) {
cout << "--";
}
cout << root->name << endl;
if (root->father != NULL) {
print(root->father, level + 1);
}
if (root->mother != NULL) {
print(root->mother, level + 1);
}
}
int main() {
TreeNode *root = NULL;
// 插入节点
insert(root, new Genealogy("爷爷"));
insert(root, new Genealogy("爸爸"));
insert(root, new Genealogy("妈妈"));
insert(root, new Genealogy("哥哥"));
insert(root, new Genealogy("弟弟"));
insert(root, new Genealogy("姐姐"));
insert(root, new Genealogy("妹妹"));
insert(root, new Genealogy("儿子"));
insert(root, new Genealogy("女儿"));
// 构建家谱
Genealogy *grandfather = search(root, "爷爷");
Genealogy *father = search(root, "爸爸");
Genealogy *mother = search(root, "妈妈");
Genealogy *son1 = search(root, "儿子");
Genealogy *daughter1 = search(root, "女儿");
Genealogy *son2 = new Genealogy("孙子");
Genealogy *daughter2 = new Genealogy("孙女");
insert(father->father, grandfather);
father->mother = new Genealogy("奶奶");
mother->father = new Genealogy("外公");
mother->mother = new Genealogy("外婆");
insert(father, son1);
insert(father, daughter1);
insert(son1, son2);
insert(daughter1, daughter2);
// 打印家谱
print(grandfather, 0);
return 0;
}
```
上述代码中,`Genealogy`结构体表示家谱节点,包括姓名和父亲母亲节点指针;`TreeNode`结构体表示二叉树节点,包括数据和左右子节点指针。`insert`函数用于插入节点,`search`函数用于查找节点,`print`函数用于打印家谱。在`main`函数中,先插入节点,然后根据关系构建家谱,最后打印家谱。
阅读全文