输入10个不同整数,依次插入到一颗初始为空的二叉排序树中,并对其进行中序遍历,以验证树的正确性。用c代码实现
时间: 2024-02-13 07:05:17 浏览: 19
好的,以下是对应的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 inorder(TreeNode* root) {
if (root == NULL) {
return;
}
inorder(root->left);
printf("%d ", root->val);
inorder(root->right);
}
int main() {
TreeNode* root = NULL;
int arr[10] = {5, 2, 8, 1, 4, 7, 9, 3, 6, 10};
for (int i = 0; i < 10; i++) {
root = insert(root, arr[i]);
}
inorder(root);
return 0;
}
```
这段代码会先定义一个二叉排序树的结点结构体`TreeNode`,然后依次将输入的10个不同整数插入到二叉排序树中。最后对二叉排序树进行中序遍历,以验证树的正确性。