C语言二叉树每个节点的左右子树高度和的最大值
时间: 2024-05-07 17:22:42 浏览: 82
要求二叉树每个节点的左右子树高度和的最大值,需要遍历每个节点并计算其左右子树的高度,再将左右子树高度相加得到该节点的左右子树高度和,最终比较所有节点的左右子树高度和,输出最大值即可。
具体实现可以使用递归的方式遍历二叉树,在递归的过程中计算每个节点的左右子树高度和,并更新最大值。递归函数可以返回当前节点的高度,以便在计算父节点的高度时使用。
以下是C语言实现的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
int max(int a, int b) {
return a > b ? a : b;
}
int getHeight(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
return max(leftHeight, rightHeight) + 1;
}
int maxSum(TreeNode* root, int* maxSumValue) {
if (root == NULL) {
return 0;
}
int leftSum = maxSum(root->left, maxSumValue);
int rightSum = maxSum(root->right, maxSumValue);
int sum = leftSum + rightSum + root->val;
if (sum > *maxSumValue) {
*maxSumValue = sum;
}
return max(leftSum, rightSum) + root->val;
}
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 = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
int maxSumValue = 0;
maxSum(root, &maxSumValue);
printf("Max sum of left and right subtree heights: %d\n", maxSumValue);
free(root->left);
free(root->right->left);
free(root->right->right);
free(root->right);
free(root);
return 0;
}
```
以上代码中,`getHeight`函数计算二叉树的高度,`maxSum`函数使用递归计算每个节点的左右子树高度和,并更新最大值。在`main`函数中,构造了一个示例二叉树,并输出了左右子树高度和的最大值。
阅读全文