c语言求二叉树最大值
时间: 2023-07-02 14:16:08 浏览: 38
假设二叉树的节点结构体为:
```c
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
```
可以使用递归的方式求解二叉树的最大值,具体实现如下:
```c
int maxVal(struct TreeNode* root) {
if (root == NULL) {
return INT_MIN;
}
int leftMax = maxVal(root->left);
int rightMax = maxVal(root->right);
return fmax(fmax(leftMax, rightMax), root->val);
}
```
首先判断当前节点是否为空,如果为空则返回INT_MIN,表示该分支没有取到任何节点的值。如果不为空,则分别递归求解左子树和右子树的最大值,并将其与当前节点的值取最大值返回。
相关问题
c语言求二叉树节点的最大值
以下是求二叉树节点最大值的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
typedef struct node {
int value;
struct node *left;
struct node *right;
} node;
// 创建一个新的节点
node *new_node(int value) {
node *n = (node *) malloc(sizeof(node));
n->value = value;
n->left = NULL;
n->right = NULL;
return n;
}
// 按照给定的数值插入到二叉树中
void insert(node **root, int value) {
if (*root == NULL) {
*root = new_node(value);
return;
}
if (value < (*root)->value) {
insert(&(*root)->left, value);
} else {
insert(&(*root)->right, value);
}
}
// 递归求二叉树节点最大值
int max_value(node *root) {
if (root == NULL) {
return -1;
} else if (root->right == NULL) {
return root->value;
} else {
return max_value(root->right);
}
}
int main() {
node *root = NULL;
insert(&root, 5);
insert(&root, 3);
insert(&root, 7);
insert(&root, 1);
insert(&root, 9);
printf("最大值为:%d\n", max_value(root));
return 0;
}
```
以上代码中,通过递归求出二叉树中右子树最底层节点的值,即为二叉树节点的最大值。
C语言求二叉树以元素值为x的节点为根的子树深度代码
以下是C语言求二叉树以元素值为x的节点为根的子树深度的代码实现:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
int subtreeDepth(TreeNode* root, int x) {
if (root == NULL) {
return 0;
}
if (root->val == x) {
return maxDepth(root);
}
int leftDepth = subtreeDepth(root->left, x);
int rightDepth = subtreeDepth(root->right, x);
return leftDepth > rightDepth ? leftDepth : rightDepth;
}
int maxDepth(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
}
int main() {
// 构建二叉树
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = NULL;
int x = 3;
int depth = subtreeDepth(root, x);
printf("Subtree depth for node with val %d is %d\n", x, depth);
return 0;
}
```
该代码实现了一个查找二叉树中以元素值为x的节点为根的子树深度的函数subtreeDepth,并且使用了maxDepth函数来计算最大深度。如果节点查找失败或者树为空,subtreeDepth函数会返回0。