用C语言对二叉排序树,分别给出测试案例查找成功和查找失败的查找次数,用代码显示出来
时间: 2024-05-03 16:21:37 浏览: 42
数据结构 课程设计 二叉排序树查找C语言代码1 含测试序列.doc
二叉排序树的查找成功和查找失败的查找次数取决于树的结构和所查找的节点。以下是一个简单的二叉排序树的实现,包含了查找成功和查找失败的测试案例,并输出了对应的查找次数。
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
int search(TreeNode *root, int target, int *count) {
if (root == NULL) {
return 0; // 查找失败
}
if (root->val == target) {
(*count)++; // 查找成功
return 1;
}
if (root->val > target) {
(*count)++;
return search(root->left, target, count);
} else {
(*count)++;
return search(root->right, target, count);
}
}
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;
}
int main() {
TreeNode *root = NULL;
root = insert(root, 4);
root = insert(root, 2);
root = insert(root, 6);
root = insert(root, 1);
root = insert(root, 3);
root = insert(root, 5);
root = insert(root, 7);
int count = 0;
int target = 5;
int found = search(root, target, &count);
if (found) {
printf("查找成功,查找次数:%d\n", count);
} else {
printf("查找失败,查找次数:%d\n", count);
}
count = 0;
target = 8;
found = search(root, target, &count);
if (found) {
printf("查找成功,查找次数:%d\n", count);
} else {
printf("查找失败,查找次数:%d\n", count);
}
return 0;
}
```
输出结果为:
```
查找成功,查找次数:3
查找失败,查找次数:3
```
说明在该二叉排序树中,查找值为5的节点需要3次比较,查找值为8的节点也需要3次比较,但是最终查找失败。
阅读全文