用c语言,给定一个二叉树,求二叉树从根节点到叶节点路径和最大值
时间: 2024-01-23 08:06:01 浏览: 85
用C语言求二叉树叶子结点
4星 · 用户满意度95%
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
int maxPathSum(struct TreeNode* root) {
if (root == NULL) return 0;
int leftMax = maxPathSum(root->left); // 左子树的最大路径和
int rightMax = maxPathSum(root->right); // 右子树的最大路径和
int maxSum = root->val; // 当前节点的最大路径和
if (leftMax > 0) maxSum += leftMax;
if (rightMax > 0) maxSum += rightMax;
return maxSum;
}
int main() {
// 创建二叉树
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->right->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
int maxSum = maxPathSum(root);
printf("The maximum path sum is %d\n", maxSum);
return 0;
}
阅读全文