用c语言输入一组数据到二叉树里 然后输出一个最大的节点,打出运行结果
时间: 2023-04-04 21:04:44 浏览: 59
好的,这个问题我可以回答。以下是代码:
```
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* createNode(int val) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
void insert(struct TreeNode** root, int val) {
if (*root == NULL) {
*root = createNode(val);
return;
}
if (val < (*root)->val) {
insert(&((*root)->left), val);
} else {
insert(&((*root)->right), val);
}
}
int findMax(struct TreeNode* root) {
if (root == NULL) {
return -1;
}
while (root->right != NULL) {
root = root->right;
}
return root->val;
}
int main() {
struct TreeNode* root = NULL;
int n, val;
printf("请输入数据的个数:");
scanf("%d", &n);
printf("请输入数据:");
for (int i = 0; i < n; i++) {
scanf("%d", &val);
insert(&root, val);
}
int max = findMax(root);
printf("最大的节点是:%d\n", max);
return 0;
}
```
假设输入数据为:5 3 7 1 4 6 8,运行结果为:
```
请输入数据的个数:7
请输入数据:5 3 7 1 4 6 8
最大的节点是:8
```