写一段c语言测试代码插入int main() { int arr[] = {3, 1, 4, 6, 9, 2, 5, 7, 6, 10}到一颗空树
时间: 2023-10-03 14:05:58 浏览: 116
好的,为您编写以下代码:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int value;
struct Node* left;
struct Node* right;
};
void insert(struct Node** root, int value) {
if (*root == NULL) {
// Create a new node and set the value
struct Node* node = (struct Node*) malloc(sizeof(struct Node));
node->value = value;
node->left = NULL;
node->right = NULL;
*root = node;
}
else {
// Traverse the tree to find the correct position to insert the value
if (value < (*root)->value) {
insert(&(*root)->left, value);
}
else {
insert(&(*root)->right, value);
}
}
}
void printInOrder(struct Node* root) {
if (root != NULL) {
printInOrder(root->left);
printf("%d ", root->value);
printInOrder(root->right);
}
}
int main() {
int arr[] = {3, 1, 4, 6, 9, 2, 5, 7, 6, 10};
int n = sizeof(arr) / sizeof(arr[0]);
// Insert each value in the array into a binary search tree
struct Node* root = NULL;
for (int i = 0; i < n; i++) {
insert(&root, arr[i]);
}
// Print the values in order
printInOrder(root);
return 0;
}
```
请注意,这是一个简单的插入值到二叉搜索树的示例代码。这个代码可能不是最优的实现,但它能很好地演示如何将值插入到一颗空树中,并按顺序打印树中的值。
阅读全文