C语言源程序查找算法的实现: 任意输入一组数据作为二叉排序树中结点的键值,创建一棵二叉排序树,然后对给定的值进行查找。
时间: 2024-02-06 09:11:44 浏览: 102
好的,我可以为您解答。以下是C语言源程序查找算法的实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉排序树结点的数据结构
struct TreeNode {
int value;
struct TreeNode* left;
struct TreeNode* right;
};
// 创建新结点
struct TreeNode* createNode(int value) {
struct TreeNode* node = (struct TreeNode*) malloc(sizeof(struct TreeNode));
node->value = value;
node->left = NULL;
node->right = NULL;
return node;
}
// 插入结点
struct TreeNode* insertNode(struct TreeNode* root, int value) {
if (root == NULL) {
return createNode(value);
}
if (value < root->value) {
root->left = insertNode(root->left, value);
} else if (value > root->value) {
root->right = insertNode(root->right, value);
}
return root;
}
// 查找结点
struct TreeNode* searchNode(struct TreeNode* root, int value) {
if (root == NULL || root->value == value) {
return root;
}
if (value < root->value) {
return searchNode(root->left, value);
} else {
return searchNode(root->right, value);
}
}
// 中序遍历二叉排序树
void inorderTraversal(struct TreeNode* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->value);
inorderTraversal(root->right);
}
}
int main() {
struct TreeNode* root = NULL;
int n, value, searchValue;
// 读入数据
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &value);
root = insertNode(root, value);
}
// 中序遍历二叉排序树
printf("Inorder traversal of the tree: ");
inorderTraversal(root);
printf("\n");
// 查找给定的值
printf("Enter the value to search: ");
scanf("%d", &searchValue);
struct TreeNode* result = searchNode(root, searchValue);
if (result == NULL) {
printf("%d not found in the tree\n", searchValue);
} else {
printf("%d found in the tree\n", searchValue);
}
return 0;
}
```
该程序中,我们定义了一个 `struct TreeNode` 结构体表示二叉排序树的结点,包括结点的值和左右子结点指针。`createNode()` 函数用于创建新结点,`insertNode()` 函数用于插入结点,`searchNode()` 函数用于查找结点。`inorderTraversal()` 函数用于中序遍历二叉排序树。在 `main()` 函数中,我们首先读入数据并创建二叉排序树,然后进行中序遍历并输出结果。最后,我们读入给定值并在二叉排序树中查找该值,输出查找结果。
希望这个程序可以帮助到您!
阅读全文
相关推荐

















