使用c语言将一组数据写入二叉树并输出最小的数
时间: 2023-04-04 22:05:01 浏览: 53
您好,我可以回答这个问题。以下是使用 C 语言将一组数据写入二叉树并输出最小的数的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 插入节点
void insert(TreeNode **root, int val) {
if (*root == NULL) {
*root = (TreeNode *)malloc(sizeof(TreeNode));
(*root)->val = val;
(*root)->left = NULL;
(*root)->right = NULL;
} else if (val < (*root)->val) {
insert(&((*root)->left), val);
} else {
insert(&((*root)->right), val);
}
}
// 查找最小值
int findMin(TreeNode *root) {
while (root->left != NULL) {
root = root->left;
}
return root->val;
}
int main() {
int nums[] = {5, 3, 7, 1, 9, 4, 2};
int len = sizeof(nums) / sizeof(nums[0]);
TreeNode *root = NULL;
for (int i = 0; i < len; i++) {
insert(&root, nums[i]);
}
int min = findMin(root);
printf("最小值为:%d\n", min);
return 0;
}
```
希望能够帮到您!