C语言实现查找数据37和20是否存在,若存在输出提示,若不存在,则将该数据插入二叉排序树中
时间: 2024-02-15 08:05:01 浏览: 21
好的,下面是C语言的实现示例。这里我们需要在插入数据的基础上,增加查找数据的功能。
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 插入节点
TreeNode* insert(TreeNode* root, int val) {
if (root == NULL) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
if (val < root->val) {
root->left = insert(root->left, val);
} else {
root->right = insert(root->right, val);
}
return root;
}
// 中序遍历
void inorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
// 查找节点
void search(TreeNode* root, int val) {
if (root == NULL) {
printf("数据 %d 不存在,将其插入二叉排序树中。\n", val);
insert(root, val);
return;
}
if (root->val == val) {
printf("数据 %d 存在!\n", val);
return;
}
if (val < root->val) {
search(root->left, val);
} else {
search(root->right, val);
}
}
int main() {
TreeNode* root = NULL;
int elements[] = {5, 2, 1, 6, 8, 3, 7, 4, 9};
int length = sizeof(elements) / sizeof(elements[0]);
for (int i = 0; i < length; i++) {
root = insert(root, elements[i]);
}
inorderTraversal(root);
printf("\n");
search(root, 37);
search(root, 20);
inorderTraversal(root);
return 0;
}
```
在这个示例代码中,我们在插入函数的基础上,增加了一个查找函数 `search`。首先判断当前节点是否为空,如果为空则说明这个数据不存在,就输出提示并将其插入到二叉排序树中。否则判断当前节点的值是否等于要查找的值,如果是则说明这个数据存在,就输出提示。否则根据要查找的值与当前节点的大小关系,递归查找左子树或右子树。
在 `main` 函数中,我们先创建一个空的根节点,然后逐个插入数据元素。最终,我们调用 `inorderTraversal` 函数对树进行中序遍历,并将结果输出到控制台上。接着,我们分别查找数据37和20是否存在,并输出相应的提示信息。最后,再次调用 `inorderTraversal` 函数,输出插入后的中序遍历结果。
希望这个示例代码能够帮助您理解如何在C语言中查找数据并插入二叉排序树中!