用C语言编程实现在二叉排序树中进行查找。读入一串整数,采用二叉链存储结构创建一棵二叉排序树,给定一个值,在二叉排序树中进行查找,输出查找结果,给定具体数据调试程序。
时间: 2025-02-04 19:29:25 浏览: 48
好的,我来为您介绍如何使用C语言在二叉排序树中进行查找,并提供一个完整的程序示例。
首先,让我们了解一下二叉排序树的基本概念:
二叉排序树是一种特殊的二叉树,它的左子树所有节点的值都小于根节点的值,右子树所有节点的值都大于根节点的值。这样可以保证中序遍历二叉排序树时会得到一个有序序列。
下面是一个实现二叉排序树查找的C语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉排序树的节点结构
typedef struct BSTNode {
int data;
struct BSTNode *left, *right;
} BSTNode;
// 创建一个新的二叉排序树节点
BSTNode* createNode(int data) {
BSTNode* newNode = (BSTNode*)malloc(sizeof(BSTNode));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// 插入节点到二叉排序树
BSTNode* insert(BSTNode* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data);
}
// 如果数据已经存在,不进行插入
return root;
}
// 在二叉排序树中查找一个值
BSTNode* search(BSTNode* root, int key) {
if (root == NULL || root->data == key) {
return root;
}
if (key < root->data) {
return search(root->left, key);
} else {
return search(root->right, key);
}
}
// 中序遍历二叉排序树
void inorder(BSTNode* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
int main() {
BSTNode* root = NULL;
int n, value, key;
printf("请输入要插入的整数个数: ");
scanf("%d", &n);
printf("请输入 %d 个整数: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &value);
root = insert(root, value);
}
printf("二叉排序树的中序遍历结果: ");
inorder(root);
printf("\n");
printf("请输入要查找的整数: ");
scanf("%d", &key);
BSTNode* result = search(root, key);
if (result != NULL) {
printf("找到 %d 在二叉排序树中。\n", key);
} else {
printf("未找到 %d 在二叉排序树中。\n", key);
}
return 0;
}
```
这个程序首先定义了一个二叉排序树节点结构,然后实现了创建新节点、插入节点和中序遍历的函数。核心的查找函数`search`使用递归的方式在二叉排序树中查找指定的值。
在`main`函数中,程序首先读取用户输入的整数并构建二叉排序树,然后进行中序遍历输出结果。最后,程序提示用户输入要查找的整数,并输出查找结果。
使用这个程序时,你可以输入任意数量的整数来构建二叉排序树,然后输入要查找的整数,程序会告诉你该整数是否存在于二叉排序树中。
阅读全文
相关推荐


















