用c语言输入一组数据到二叉树里 然后输出一个最大的节点
时间: 2023-04-04 13:04:40 浏览: 58
您好,我可以回答这个问题。以下是用 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 findMax(TreeNode *root) {
if (root == NULL) {
return -1;
}
while (root->right != NULL) {
root = root->right;
}
return root->val;
}
int main() {
TreeNode *root = NULL;
int n, val;
printf("请输入数据的个数:");
scanf("%d", &n);
printf("请输入%d个数据:", n);
for (int i = 0; i < n; i++) {
scanf("%d", &val);
insert(&root, val);
}
int max = findMax(root);
printf("最大的节点是:%d\n", max);
return 0;
}
```
希望能够帮到您!