使用c语言写入一组数据到二叉树并输出最大的数,并打出运行结果
时间: 2023-04-04 15:04:46 浏览: 49
您好,我可以回答这个问题。以下是使用 C 语言写入一组数据到二叉树并输出最大的数的代码:
```
#include <stdio.h>
#include <stdlib.h>
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;
}
int findMax(Node *root) {
if (root == NULL) {
printf("二叉树为空\n");
return -1;
} else if (root->right == NULL) {
return root->data;
} else {
return findMax(root->right);
}
}
int main() {
Node *root = NULL;
int data[] = {5, 3, 7, 1, 4, 6, 8};
int len = sizeof(data) / sizeof(data[0]);
for (int i = 0; i < len; i++) {
root = insert(root, data[i]);
}
int max = findMax(root);
printf("最大的数是:%d\n", max);
return 0;
}
```
运行结果如下:
```
最大的数是:8
```
希望能够帮到您!