重新说明一下,如何完成各种搜索树效率比较的代码,请使用C语言将其实现,不需要太多的文字补充说明,只需要提供全代码过程
时间: 2023-06-16 14:06:13 浏览: 40
以下是使用C语言编写的搜索树效率比较代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 100000
typedef struct node {
int data;
struct node *left;
struct node *right;
} Node;
Node *createNode(int data) {
Node *newNode = (Node *) malloc(sizeof(Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
Node *insert(Node *root, int data) {
if (root == NULL) {
return createNode(data);
} else if (data <= root->data) {
root->left = insert(root->left, data);
} else {
root->right = insert(root->right, data);
}
return root;
}
Node *search(Node *root, int data) {
if (root == NULL) {
return NULL;
} else if (root->data == data) {
return root;
} else if (data <= root->data) {
return search(root->left, data);
} else {
return search(root->right, data);
}
}
Node *minValueNode(Node *node) {
Node *current = node;
while (current->left != NULL) {
current = current->left;
}
return current;
}
Node *delete(Node *root, int data) {
if (root == NULL) {
return root;
} else if (data < root->data) {
root->left = delete(root->left, data);
} else if (data > root->data) {
root->right = delete(root->right, data);
} else {
if (root->left == NULL) {
Node *temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
Node *temp = root->left;
free(root);
return temp;
}
Node *temp = minValueNode(root->right);
root->data = temp->data;
root->right = delete(root->right, temp->data);
}
return root;
}
void inorderTraversal(Node *root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
void preorderTraversal(Node *root) {
if (root == NULL) {
return;
}
printf("%d ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
void postorderTraversal(Node *root) {
if (root == NULL) {
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->data);
}
int main() {
int i, num;
Node *root = NULL;
clock_t start, end;
double time;
srand(time(NULL));
// Insertion
start = clock();
for (i = 0; i < MAX; i++) {
num = rand() % MAX;
root = insert(root, num);
}
end = clock();
time = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Insertion time: %f seconds\n", time);
// Search
start = clock();
for (i = 0; i < MAX; i++) {
num = rand() % MAX;
search(root, num);
}
end = clock();
time = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Search time: %f seconds\n", time);
// Deletion
start = clock();
for (i = 0; i < MAX; i++) {
num = rand() % MAX;
root = delete(root, num);
}
end = clock();
time = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Deletion time: %f seconds\n", time);
return 0;
}
```
在代码中,我们使用了二叉搜索树来进行比较,实现了插入、搜索和删除等操作。我们使用了 `clock()` 函数来计算代码运行的时间,从而比较各个操作的效率。最后输出了各个操作的时间。