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.

这道题一开始没看懂题目什么意思,后来才明白是:把树看成是无向图,求一条路径,使得这条路径上结点val之和最大(此路径的val之和称为最大路径和),当然路径可以只含一个点。

tempMax保存当前找到的最大路径和,基于二叉树的遍历(深度优先),如下

getMax(*root)返回以root为根的子树中包含root且最多只包含root的一个子分支的路径的最大路径和(是个局部值),这个函数中会修改最大路径和tempMax。

maxL为左子树的最大路径和,

maxR为右子树的最大路径和,

如果val+max(0,maxL,maxR,maxL+maxR)>tempMax,那么更新tempMax

返回val +max(maxL,maxR,0) ,注意只能最多包含一个分支,否则包含两个分支的话,路径就确定了,返回给上层就不能再构建路径。


最后tempMax即为所求。

代码如下:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    static int tempMax;
    /*返回包含本结点的最大路径*/
    int getMax(TreeNode *root){
        if(NULL==root)
            return 0;
        if(!root->left&&!root->right){/*leaf node*/
            tempMax=root->val>tempMax?root->val:tempMax;
            return root->val;
        }
        int maxL=getMax(root->left);
        int maxR=getMax(root->right);
        int maxLR=std::max(maxL,maxR);
        int maxLR2=std::max(maxLR,maxL+maxR);
        int m=maxLR2>0?root->val+maxLR2:root->val;
        /*update tempMax*/
        tempMax=m>tempMax?m:tempMax;
        return maxLR>0?root->val+maxLR:root->val;
        
    }
    int maxPathSum(TreeNode *root) {
        tempMax=INT_MIN;
        getMax(root);
        /*return tempMax*/
        return tempMax;
    }
};
int Solution::tempMax=INT_MIN;





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值