按先序次序建立一颗二叉树,然后输出树中最小值,C语言代码
时间: 2024-05-21 16:12:34 浏览: 13
以下是按先序次序建立一颗二叉树并输出最小值的C语言代码:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* newNode(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
void buildTree(struct Node** root) {
int data;
printf("Enter data (or -1 for NULL): ");
scanf("%d", &data);
if (data == -1) {
*root = NULL;
return;
}
*root = newNode(data);
buildTree(&((*root)->left));
buildTree(&((*root)->right));
}
int findMin(struct Node* root) {
if (root == NULL) {
return INT_MAX;
}
int min = root->data;
int leftMin = findMin(root->left);
int rightMin = findMin(root->right);
if (leftMin < min) {
min = leftMin;
}
if (rightMin < min) {
min = rightMin;
}
return min;
}
int main() {
struct Node* root = NULL;
buildTree(&root);
int min = findMin(root);
printf("The minimum value in the binary tree is %d\n", min);
return 0;
}
注意:这是一般情况下的二叉树,如果二叉树有特殊的性质(如二叉搜索树),可以采用更高效的算法。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)