返回二叉树中最大值c语言实现函数
时间: 2024-05-05 12:22:48 浏览: 12
以下是使用递归算法实现的二叉树最大值查找函数:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结构体
typedef struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 创建节点
TreeNode* createNode(int data) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
// 递归查找二叉树最大值
int findMax(TreeNode* root) {
int maxVal = root->data;
int leftMax = INT_MIN, rightMax = INT_MIN;
if (root->left != NULL) {
leftMax = findMax(root->left);
}
if (root->right != NULL) {
rightMax = findMax(root->right);
}
if (leftMax > maxVal) {
maxVal = leftMax;
}
if (rightMax > maxVal) {
maxVal = rightMax;
}
return maxVal;
}
int main() {
// 创建二叉树
TreeNode* root = createNode(5);
root->left = createNode(3);
root->right = createNode(7);
root->left->left = createNode(1);
root->left->right = createNode(4);
root->right->left = createNode(6);
root->right->right = createNode(9);
// 查找最大值
int maxVal = findMax(root);
printf("The maximum value in the binary tree is: %d\n", maxVal);
return 0;
}
```
注意,这里使用了 `<limits.h>` 头文件中定义的 `INT_MIN` 常量,需要在程序开头添加 `#include <limits.h>`。