编写二叉树之通讯录查询系统
时间: 2023-11-27 21:54:49 浏览: 48
好的,下面是一个简单的二叉树通讯录查询系统的实现,具体实现细节可以根据需求进行调整和改进。
首先,我们定义一个通讯录联系人的结构体:
```c++
struct Contact {
string name;
string phone_number;
string email;
};
```
然后,我们定义一个二叉树节点的结构体,每个节点包含一个联系人信息和左右子节点指针:
```c++
struct TreeNode {
Contact contact;
TreeNode* left;
TreeNode* right;
};
```
接下来,我们可以实现一个函数用于向二叉树中插入联系人信息:
```c++
void insertContact(TreeNode*& root, Contact contact) {
if (root == nullptr) {
root = new TreeNode{contact, nullptr, nullptr};
} else if (contact.name < root->contact.name) {
insertContact(root->left, contact);
} else {
insertContact(root->right, contact);
}
}
```
其中,`root`为当前子树的根节点指针,`contact`为待插入的联系人信息。
为了方便查询,我们可以实现一个函数用于中序遍历二叉树,并将联系人信息按照字典序输出:
```c++
void inorderTraversal(TreeNode* root) {
if (root != nullptr) {
inorderTraversal(root->left);
cout << root->contact.name << "\t" << root->contact.phone_number << "\t" << root->contact.email << endl;
inorderTraversal(root->right);
}
}
```
最后,我们可以实现主函数,用于向二叉树中插入联系人信息,并提供一个简单的命令行界面用于查询:
```c++
int main() {
TreeNode* root = nullptr;
while (true) {
cout << "请选择操作:1-插入联系人 2-查询联系人 3-退出" << endl;
int choice;
cin >> choice;
if (choice == 1) {
Contact contact;
cout << "请输入联系人姓名:";
cin >> contact.name;
cout << "请输入联系人电话:";
cin >> contact.phone_number;
cout << "请输入联系人邮箱:";
cin >> contact.email;
insertContact(root, contact);
} else if (choice == 2) {
cout << "请输入联系人姓名:";
string name;
cin >> name;
TreeNode* node = findContact(root, name);
if (node == nullptr) {
cout << "未找到该联系人" << endl;
} else {
cout << node->contact.name << "\t" << node->contact.phone_number << "\t" << node->contact.email << endl;
}
} else if (choice == 3) {
break;
} else {
cout << "输入有误,请重新输入" << endl;
}
}
return 0;
}
```
其中,`findContact`函数可以用于在二叉树中查找指定姓名的联系人信息:
```c++
TreeNode* findContact(TreeNode* root, string name) {
if (root == nullptr) {
return nullptr;
} else if (root->contact.name == name) {
return root;
} else if (name < root->contact.name) {
return findContact(root->left, name);
} else {
return findContact(root->right, name);
}
}
```
以上就是一个简单的二叉树通讯录查询系统的实现。当然,实际使用中还需要考虑数据存储、界面设计、输入验证、错误处理等方面的问题。