[Leetcode] Binary Tree Maximum Path Sum

本文介绍了一种求解二叉树中最大路径和的算法实现。通过后序遍历的方法,递归地计算每个节点的最大贡献值,并更新全局最大路径和。此算法能够有效地找到从任意节点开始和结束的最大路径。

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1
      / \
     2   3

 

Return 6.

后序遍历!

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int myMax(int a, int b, int c) {
13         a = a > b ? a : b;
14         return a > c ? a : c;
15     }
16     
17     int getMaxSum(TreeNode *root, int &max_sum) {
18         if (root == NULL) {
19             return 0;
20         }
21         int local_max = root->val;
22         int left = getMaxSum(root->left, max_sum);
23         int right = getMaxSum(root->right, max_sum);
24         local_max += (left > 0) ? left : 0;
25         local_max += (right > 0) ? right : 0;
26         max_sum = max_sum > local_max ? max_sum : local_max;
27         return myMax(root->val, root->val + left, root->val + right);
28     }
29     
30     int maxPathSum(TreeNode *root) {
31         int max_sum = INT_MIN;
32         getMaxSum(root, max_sum);
33         return max_sum;
34     }
35 };

 

转载于:https://www.cnblogs.com/easonliu/p/3642942.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值