C++代码实现界面化二叉排序树动态查找表
时间: 2023-11-30 19:13:33 浏览: 67
以下是一个简单的 C++ 代码实现界面化二叉排序树动态查找表的示例:
```cpp
#include <iostream>
#include <cstdlib>
using namespace std;
// 定义二叉排序树的节点结构体
struct TreeNode {
int value;
TreeNode* left;
TreeNode* right;
};
// 插入节点
void InsertNode(TreeNode*& root, int value) {
if (root == NULL) {
root = new TreeNode;
root->value = value;
root->left = NULL;
root->right = NULL;
} else if (value < root->value) {
InsertNode(root->left, value);
} else {
InsertNode(root->right, value);
}
}
// 查找节点
TreeNode* FindNode(TreeNode* root, int value) {
if (root == NULL || root->value == value) {
return root;
} else if (value < root->value) {
return FindNode(root->left, value);
} else {
return FindNode(root->right, value);
}
}
// 删除节点
void DeleteNode(TreeNode*& root, int value) {
if (root == NULL) {
return;
} else if (value < root->value) {
DeleteNode(root->left, value);
} else if (value > root->value) {
DeleteNode(root->right, value);
} else {
if (root->left == NULL) {
TreeNode* temp = root;
root = root->right;
delete temp;
} else if (root->right == NULL) {
TreeNode* temp = root;
root = root->left;
delete temp;
} else {
TreeNode* temp = root->right;
while (temp->left != NULL) {
temp = temp->left;
}
root->value = temp->value;
DeleteNode(root->right, temp->value);
}
}
}
// 中序遍历二叉排序树
void InOrderTraversal(TreeNode* root) {
if (root != NULL) {
InOrderTraversal(root->left);
cout << root->value << " ";
InOrderTraversal(root->right);
}
}
// 释放二叉排序树内存
void FreeTree(TreeNode* root) {
if (root != NULL) {
FreeTree(root->left);
FreeTree(root->right);
delete root;
}
}
int main() {
TreeNode* root = NULL;
int choice, value;
while (true) {
cout << "1. 插入节点" << endl;
cout << "2. 查找节点" << endl;
cout << "3. 删除节点" << endl;
cout << "4. 中序遍历" << endl;
cout << "5. 退出" << endl;
cout << "请选择操作:";
cin >> choice;
switch (choice) {
case 1:
cout << "请输入要插入的元素值:";
cin >> value;
InsertNode(root, value);
break;
case 2:
cout << "请输入要查找的元素值:";
cin >> value;
if (FindNode(root, value) != NULL) {
cout << "元素值 " << value << " 存在于二叉排序树中" << endl;
} else {
cout << "元素值 " << value << " 不存在于二叉排序树中" << endl;
}
break;
case 3:
cout << "请输入要删除的元素值:";
cin >> value;
DeleteNode(root, value);
break;
case 4:
cout << "中序遍历结果为:";
InOrderTraversal(root);
cout << endl;
break;
case 5:
FreeTree(root);
exit(0);
default:
cout << "无效操作,请重新输入" << endl;
break;
}
}
return 0;
}
```
这份代码实现了二叉排序树的插入、查找、删除和中序遍历操作,并提供了一个简单的命令行界面。您可以根据需要进行修改和扩展。
阅读全文